forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_test.go
523 lines (431 loc) · 12.5 KB
/
file_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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package bundle
import (
"bytes"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/open-policy-agent/opa/internal/file/archive"
"github.com/open-policy-agent/opa/loader/filter"
"github.com/open-policy-agent/opa/util/test"
)
const testReadLimit = (1024 * 1024) + 1
var archiveFiles = map[string]string{
"/a.json": "a",
"/a/b.json": "b",
"/a/b/c.json": "c",
"/a/b/d/data.json": "hello",
"/a/c/data.yaml": "12",
"/some.txt": "text",
"/policy.rego": "package foo\n p = 1",
"/roles/policy.rego": "package bar\n p = 1",
"/deeper/dir/path/than/others/foo": "bar",
}
func TestTarballLoader(t *testing.T) {
files := map[string]string{
"/archive.tar.gz": "",
}
test.WithTempFS(files, func(rootDir string) {
tarballFile := filepath.Join(rootDir, "archive.tar.gz")
f := testGetTarballFile(t, rootDir)
loader := NewTarballLoaderWithBaseURL(f, tarballFile)
defer f.Close()
testLoader(t, loader, tarballFile, archiveFiles)
})
}
func TestIterator(t *testing.T) {
files := make([][2]string, 0, len(archiveFiles))
for name, content := range archiveFiles {
files = append(files, [2]string{name, content})
}
buf := archive.MustWriteTarGz(files)
bundle, err := NewReader(buf).WithLazyLoadingMode(true).Read()
if err != nil {
t.Fatal(err)
}
iterator := NewIterator(bundle.Raw)
fileCount := 0
for {
_, err := iterator.Next()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
fileCount++
}
expCount := 4
if fileCount != expCount {
t.Fatalf("Expected to read %d files, read %d", expCount, fileCount)
}
}
func TestIteratorOrder(t *testing.T) {
var archFiles = map[string]string{
"/a/b/c/data.json": "[1,2,3]",
"/a/b/d/e/data.json": `e: true`,
"/data.json": `{"x": {"y": true}, "a": {"b": {"z": true}}}}`,
"/a/b/y/x/z/data.yaml": `foo: 1`,
"/a/b/data.json": "[4,5,6]",
"/a/data.json": "hello",
"/policy.rego": "package foo\n p = 1",
"/roles/policy.rego": "package bar\n p = 1",
}
files := make([][2]string, 0, len(archFiles))
for name, content := range archFiles {
files = append(files, [2]string{name, content})
}
buf := archive.MustWriteTarGz(files)
bundle, err := NewReader(buf).WithLazyLoadingMode(true).Read()
if err != nil {
t.Fatal(err)
}
iterator := NewIterator(bundle.Raw)
fileCount := 0
actualDataFiles := []string{}
for {
i, err := iterator.Next()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
fileCount++
if !strings.HasSuffix(i.Path.String(), RegoExt) {
actualDataFiles = append(actualDataFiles, i.Path.String())
}
}
expCount := 8
if fileCount != expCount {
t.Fatalf("Expected to read %d files, read %d", expCount, fileCount)
}
expDataFiles := []string{"/", "/a", "/a/b", "/a/b/c", "/a/b/d/e", "/a/b/y/x/z"}
if !reflect.DeepEqual(expDataFiles, actualDataFiles) {
t.Fatalf("Expected data files %v but got %v", expDataFiles, actualDataFiles)
}
}
func TestDirectoryLoader(t *testing.T) {
test.WithTempFS(archiveFiles, func(rootDir string) {
loader := NewDirectoryLoader(rootDir)
testLoader(t, loader, rootDir, archiveFiles)
})
}
func TestTarballLoaderWithFilter(t *testing.T) {
files := map[string]string{
"/a/data.json": `{"foo": "not-bar"}`,
"/policy.rego": "package foo\n p = 1",
"/policy_test.rego": "package foo\n test_p { p }",
"/a/b/c/policy.rego": "package bar\n q = 1",
"/a/b/c/policy_test.rego": "package bar\n test_q { q }",
"/a/.manifest": `{"roots": ["a", "foo"]}`,
}
expectedFiles := map[string]string{
"/a/data.json": `{"foo": "not-bar"}`,
"/policy.rego": "package foo\n p = 1",
"/a/b/c/policy.rego": "package bar\n q = 1",
"/a/.manifest": `{"roots": ["a", "foo"]}`,
}
gzFileIn := map[string]string{
"/archive.tar.gz": "",
}
test.WithTempFS(gzFileIn, func(rootDir string) {
tarballFile := filepath.Join(rootDir, "archive.tar.gz")
f, err := os.Create(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
gzFiles := make([][2]string, 0, len(files))
for name, content := range files {
gzFiles = append(gzFiles, [2]string{name, content})
}
_, err = f.Write(archive.MustWriteTarGz(gzFiles).Bytes())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
f.Close()
f, err = os.Open(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
loader := NewTarballLoaderWithBaseURL(f, tarballFile).WithFilter(func(abspath string, info os.FileInfo, depth int) bool {
return getFilter("*_test.rego", 1)(abspath, info, depth)
})
defer f.Close()
testLoader(t, loader, tarballFile, expectedFiles)
})
}
func TestTarballLoaderWithFilterDir(t *testing.T) {
files := map[string]string{
"/a/data.json": `{"foo": "not-bar"}`,
"/policy.rego": "package foo\n p = 1",
"/policy_test.rego": "package foo\n test_p { p }",
"/a/b/c/policy.rego": "package bar\n q = 1",
"/a/b/c/policy_test.rego": "package bar\n test_q { q }",
"/a/.manifest": `{"roots": ["a", "foo"]}`,
}
expectedFiles := map[string]string{
"/policy.rego": "package foo\n p = 1",
}
gzFileIn := map[string]string{
"/archive.tar.gz": "",
}
test.WithTempFS(gzFileIn, func(rootDir string) {
tarballFile := filepath.Join(rootDir, "archive.tar.gz")
f, err := os.Create(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
gzFiles := make([][2]string, 0, len(files))
for name, content := range files {
gzFiles = append(gzFiles, [2]string{name, content})
}
_, err = f.Write(archive.MustWriteTarGz(gzFiles).Bytes())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
f.Close()
f, err = os.Open(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
loader := NewTarballLoaderWithBaseURL(f, tarballFile).WithFilter(func(abspath string, info os.FileInfo, depth int) bool {
return getFilter("*_test.rego", 1)(abspath, info, depth)
})
defer f.Close()
tl, ok := loader.(*tarballLoader)
if !ok {
t.Fatal("Expected tar loader instance")
}
tl.skipDir = map[string]struct{}{"a": {}}
fileCount := 0
for {
f, err := tl.NextFile()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
expPath := strings.TrimPrefix(f.URL(), tarballFile)
if f.Path() != expPath {
t.Fatalf("Expected path to be %v but got %v", expPath, f.Path())
}
_, found := expectedFiles[f.Path()]
if !found {
t.Fatalf("Found unexpected file %s", f.Path())
}
fileCount++
}
if fileCount != len(expectedFiles) {
t.Fatalf("Expected to read %d files, read %d", len(expectedFiles), fileCount)
}
})
}
func TestDirectoryLoaderWithFilter(t *testing.T) {
files := map[string]string{
"/a/data.json": `{"foo": "not-bar"}`,
"/policy.rego": "package foo\n p = 1",
"/policy_test.rego": "package foo\n test_p { p }",
"/a/b/c/policy.rego": "package bar\n q = 1",
"/a/b/c/policy_test.rego": "package bar\n test_q { q }",
"/a/.manifest": `{"roots": ["a", "foo"]}`,
}
expectedFiles := map[string]struct{}{
"/a/data.json": {},
"/policy.rego": {},
"/a/b/c/policy.rego": {},
"/a/.manifest": {},
}
test.WithTempFS(files, func(rootDir string) {
dl := NewDirectoryLoader(rootDir).WithFilter(func(abspath string, info os.FileInfo, depth int) bool {
return getFilter("*_test.rego", 1)(abspath, info, depth)
})
fileCount := 0
for {
f, err := dl.NextFile()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
expPath := strings.TrimPrefix(f.URL(), rootDir)
if f.Path() != expPath {
t.Fatalf("Expected path to be %v but got %v", expPath, f.Path())
}
_, found := expectedFiles[f.Path()]
if !found {
t.Fatalf("Found unexpected file %s", f.Path())
}
fileCount++
}
if fileCount != len(expectedFiles) {
t.Fatalf("Expected to read %d files, read %d", len(expectedFiles), fileCount)
}
})
}
func TestDirectoryLoaderWithFilterDir(t *testing.T) {
files := map[string]string{
"/a/data.json": `{"foo": "not-bar"}`,
"/policy.rego": "package foo\n p = 1",
"/policy_test.rego": "package foo\n test_p { p }",
"/a/b/c/policy.rego": "package bar\n q = 1",
"/a/b/c/policy_test.rego": "package bar\n test_q { q }",
"/a/.manifest": `{"roots": ["a", "foo"]}`,
}
expectedFiles := map[string]struct{}{
"/policy.rego": {},
"/policy_test.rego": {},
}
test.WithTempFS(files, func(rootDir string) {
dl := NewDirectoryLoader(rootDir).WithFilter(func(abspath string, info os.FileInfo, depth int) bool {
return getFilter("a", 1)(abspath, info, depth)
})
fileCount := 0
for {
f, err := dl.NextFile()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
expPath := strings.TrimPrefix(f.URL(), rootDir)
if f.Path() != expPath {
t.Fatalf("Expected path to be %v but got %v", expPath, f.Path())
}
_, found := expectedFiles[f.Path()]
if !found {
t.Fatalf("Found unexpected file %s", f.Path())
}
fileCount++
}
if fileCount != len(expectedFiles) {
t.Fatalf("Expected to read %d files, read %d", len(expectedFiles), fileCount)
}
})
}
func testGetTarballFile(t *testing.T, root string) *os.File {
t.Helper()
tarballFile := filepath.Join(root, "archive.tar.gz")
f, err := os.Create(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
gzFiles := make([][2]string, 0, len(archiveFiles))
for name, content := range archiveFiles {
gzFiles = append(gzFiles, [2]string{name, content})
}
_, err = f.Write(archive.MustWriteTarGz(gzFiles).Bytes())
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
f.Close()
f, err = os.Open(tarballFile)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
return f
}
func testLoader(t *testing.T, loader DirectoryLoader, baseURL string, expectedFiles map[string]string) {
t.Helper()
fileCount := 0
for {
f, err := loader.NextFile()
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == io.EOF {
break
}
expPath := strings.TrimPrefix(f.URL(), baseURL)
if f.Path() != expPath {
t.Fatalf("Expected path to be %v but got %v", expPath, f.Path())
}
var buf bytes.Buffer
n, err := f.Read(&buf, testReadLimit)
f.Close() // always close, even on error
if err != nil && err != io.EOF {
t.Fatalf("Unexpected error: %s", err)
} else if err == nil && n >= testReadLimit {
t.Fatalf("Attempted to read too much data")
}
expectedContent, found := expectedFiles[f.Path()]
if !found {
t.Fatalf("Found unexpected file %s", f.Path())
}
if expectedContent != buf.String() {
t.Fatalf("Content mismatch for file %s\n\nExpected:\n%s\n\nActual:\n%s\n\n",
f.Path(), expectedContent, buf.String())
}
fileCount++
}
if fileCount != len(expectedFiles) {
t.Fatalf("Expected to read %d files, read %d", len(expectedFiles), fileCount)
}
}
func TestNewDirectoryLoaderNormalizedRoot(t *testing.T) {
cases := []struct {
note string
root string
expected string
}{
{
note: "abs",
root: "/a/b/c",
expected: "/a/b/c",
},
{
note: "trailing slash",
root: "/a/b/c/",
expected: "/a/b/c/",
},
{
note: "empty",
root: "",
expected: "",
},
{
note: "single abs",
root: "/",
expected: "/",
},
{
note: "single relative",
root: "foo",
expected: "foo",
},
{
note: "single relative dot",
root: ".",
expected: ".",
},
{
note: "single relative dot slash",
root: "./",
expected: ".",
},
{
note: "relative leading dot slash",
root: "./a/b/c",
expected: "a/b/c",
},
{
note: "relative",
root: "a/b/c",
expected: "a/b/c",
},
}
for _, tc := range cases {
t.Run(tc.note, func(t *testing.T) {
l := NewDirectoryLoader(tc.root)
actual := l.(*dirLoader).root
if actual != tc.expected {
t.Fatalf("Expected root %s got %s", tc.expected, actual)
}
})
}
}
func getFilter(pattern string, minDepth int) filter.LoaderFilter {
return func(abspath string, info os.FileInfo, depth int) bool {
match, _ := filepath.Match(pattern, info.Name())
return match && depth >= minDepth
}
}