-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstorage_validation_test.go
More file actions
658 lines (589 loc) · 19.8 KB
/
storage_validation_test.go
File metadata and controls
658 lines (589 loc) · 19.8 KB
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package adaptivetelemetryprocessor
import (
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateStoragePath_ValidPaths(t *testing.T) {
tests := []struct {
name string
storagePath string
description string
skipOnWindows bool
}{
{
name: "valid path directly under allowed directory",
storagePath: "/var/lib/nrdot-collector/state.db",
description: "Files directly under /var/lib/nrdot-collector/ should be allowed",
skipOnWindows: true,
},
{
name: "valid nested path",
storagePath: "/var/lib/nrdot-collector/data/subdir/state.db",
description: "Nested paths under /var/lib/nrdot-collector/ should be allowed",
skipOnWindows: true,
},
{
name: "valid path with multiple levels",
storagePath: "/var/lib/nrdot-collector/level1/level2/level3/state.db",
description: "Deep nesting should be allowed",
skipOnWindows: true,
},
}
switch runtime.GOOS {
case "windows":
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
}
baseDir := filepath.Join(localAppData, "nrdot-collector")
windowsTests := []struct {
name string
storagePath string
description string
}{
{
name: "valid Windows path directly under allowed directory",
storagePath: filepath.Join(baseDir, "state.db"),
description: "Files directly under %LOCALAPPDATA%\\nrdot-collector\\ should be allowed",
},
{
name: "valid Windows nested path",
storagePath: filepath.Join(baseDir, "data", "subdir", "state.db"),
description: "Nested paths under %LOCALAPPDATA%\\nrdot-collector\\ should be allowed",
},
{
name: "valid Windows path with multiple levels",
storagePath: filepath.Join(baseDir, "level1", "level2", "level3", "state.db"),
description: "Deep nesting should be allowed on Windows",
},
}
for _, tc := range windowsTests {
t.Run(tc.name, func(t *testing.T) {
err := validateStoragePath(tc.storagePath, nil)
assert.NoError(t, err, tc.description)
})
}
case "linux":
// Run Linux tests only on Linux (not macOS, which has /var as a symlink)
for _, tc := range tests {
if tc.skipOnWindows {
t.Run(tc.name, func(t *testing.T) {
err := validateStoragePath(tc.storagePath, nil)
assert.NoError(t, err, tc.description)
})
}
}
default:
// On macOS and other platforms, skip Linux-specific path tests
t.Skip("Skipping Linux-specific path tests on " + runtime.GOOS)
}
}
// TestGetDefaultStoragePath_Windows tests Windows-specific default storage path generation
func TestGetDefaultStoragePath_Windows(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Skipping Windows-specific test on non-Windows platform")
}
defaultPath := getDefaultStoragePath()
// Verify it's an absolute path
assert.True(t, filepath.IsAbs(defaultPath), "Default path should be absolute on Windows")
// Verify it contains the expected directory
assert.Contains(t, defaultPath, "nrdot-collector", "Default path should contain nrdot-collector directory")
// Verify it contains the database filename
assert.Contains(t, defaultPath, "adaptiveprocess.db", "Default path should contain the database filename")
// Verify it's in the user's local app data
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData != "" {
assert.Contains(t, defaultPath, localAppData, "Default path should be under LOCALAPPDATA")
}
}
// TestCreateDirectoryIfNotExists_Windows tests directory creation on Windows
func TestCreateDirectoryIfNotExists_Windows(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Skipping Windows-specific test on non-Windows platform")
}
// Use a temporary directory for testing
tmpDir := t.TempDir()
testDir := filepath.Join(tmpDir, "test_dir", "nested", "deep")
// Directory should not exist yet
_, err := os.Stat(testDir)
assert.True(t, os.IsNotExist(err), "Test directory should not exist initially")
// Create the directory
err = createDirectoryIfNotExists(testDir)
assert.NoError(t, err, "createDirectoryIfNotExists should succeed")
// Verify directory was created
info, err := os.Stat(testDir)
assert.NoError(t, err, "Directory should exist after creation")
assert.True(t, info.IsDir(), "Created path should be a directory")
// Calling again should be idempotent
err = createDirectoryIfNotExists(testDir)
assert.NoError(t, err, "createDirectoryIfNotExists should be idempotent")
}
func TestValidateStoragePath_InvalidPaths(t *testing.T) {
tests := []struct {
name string
storagePath string
errorContains string
description string
skipOnWindows bool
}{
{
name: "empty storage path",
storagePath: "",
errorContains: "cannot be empty",
description: "Empty paths should be rejected",
},
{
name: "relative path",
storagePath: "./state.db",
errorContains: "must be an absolute path",
description: "Relative paths should be rejected",
},
{
name: "relative path with parent traversal",
storagePath: "../state.db",
errorContains: "must be an absolute path",
description: "Relative paths with .. should be rejected",
},
{
name: "path outside allowed directory - /tmp",
storagePath: "/tmp/state.db",
errorContains: "must be under",
description: "/tmp is not allowed",
skipOnWindows: true,
},
{
name: "path outside allowed directory - /etc",
storagePath: "/etc/state.db",
errorContains: "must be under",
description: "/etc is not allowed",
skipOnWindows: true,
},
{
name: "path outside allowed directory - /var/lib/other",
storagePath: "/var/lib/other-app/state.db",
errorContains: "must be under",
description: "Other directories under /var/lib/ are not allowed",
skipOnWindows: true,
},
{
name: "path traversal attempt - parent directory",
storagePath: "/var/lib/nrdot-collector/../../../etc/passwd",
errorContains: "must be under",
description: "Path traversal with .. should be rejected after cleaning",
skipOnWindows: true,
},
{
name: "root directory",
storagePath: "/",
errorContains: "must be under",
description: "Root directory should be rejected",
skipOnWindows: true,
},
{
name: "home directory",
storagePath: "/home/user/state.db",
errorContains: "must be under",
description: "Home directories should be rejected",
skipOnWindows: true,
},
}
// Add Windows-specific invalid paths
if runtime.GOOS == "windows" {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
}
allowedDir := filepath.Join(localAppData, "nrdot-collector")
windowsTests := []struct {
name string
storagePath string
errorContains string
description string
}{
{
name: "Windows path outside allowed directory - C:\\Temp",
storagePath: "C:\\Temp\\state.db",
errorContains: "must be under",
description: "C:\\Temp is not allowed on Windows",
},
{
name: "Windows path outside allowed directory - C:\\Windows",
storagePath: "C:\\Windows\\state.db",
errorContains: "must be under",
description: "C:\\Windows is not allowed on Windows",
},
{
name: "Windows path traversal attempt",
storagePath: filepath.Join(allowedDir, "..", "..", "Windows", "System32", "config"),
errorContains: "must be under",
description: "Path traversal should be rejected on Windows",
},
{
name: "Windows path in Program Files",
storagePath: "C:\\Program Files\\nrdot-collector\\state.db",
errorContains: "must be under",
description: "Program Files is not allowed on Windows",
},
{
name: "Windows path in different user's AppData",
storagePath: "C:\\Users\\OtherUser\\AppData\\Local\\nrdot-collector\\state.db",
errorContains: "must be under",
description: "Different user's AppData should be rejected on Windows",
},
}
for _, tc := range windowsTests {
t.Run(tc.name, func(t *testing.T) {
err := validateStoragePath(tc.storagePath, nil)
assert.Error(t, err, tc.description)
if tc.errorContains != "" {
assert.Contains(t, err.Error(), tc.errorContains)
}
})
}
}
// Run platform-appropriate tests
for _, tc := range tests {
if runtime.GOOS == "windows" && tc.skipOnWindows {
continue
}
t.Run(tc.name, func(t *testing.T) {
err := validateStoragePath(tc.storagePath, nil)
assert.Error(t, err, tc.description)
if tc.errorContains != "" {
assert.Contains(t, err.Error(), tc.errorContains)
}
})
}
}
func TestCheckPathForSymlinks(t *testing.T) {
// Skip on Windows as symlinks require admin privileges
if runtime.GOOS == "windows" {
t.Skip("Skipping symlink tests on Windows")
}
// Create a temporary directory for testing
tmpDir := t.TempDir()
baseDir := filepath.Join(tmpDir, "nrdot-collector")
err := os.MkdirAll(baseDir, 0o755)
require.NoError(t, err)
// Create a real directory
realDir := filepath.Join(baseDir, "real_directory")
err = os.MkdirAll(realDir, 0o755)
require.NoError(t, err)
// Create a symlink under baseDir
symlinkPath := filepath.Join(baseDir, "symlink_dir")
err = os.Symlink(realDir, symlinkPath)
require.NoError(t, err)
tests := []struct {
name string
path string
baseDir string
expectError bool
errorContains string
}{
{
name: "normal path without symlinks",
path: filepath.Join(baseDir, "real_directory", "file.db"),
baseDir: baseDir,
expectError: false,
},
{
name: "path with symlink component",
path: filepath.Join(baseDir, "symlink_dir", "file.db"),
baseDir: baseDir,
expectError: true,
errorContains: "is a symlink",
},
{
name: "non-existent path (should not error)",
path: filepath.Join(baseDir, "nonexistent", "path", "file.db"),
baseDir: baseDir,
expectError: false,
},
{
name: "path equals base",
path: baseDir,
baseDir: baseDir,
expectError: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := checkPathForSymlinks(tc.path, tc.baseDir)
if tc.expectError {
assert.Error(t, err)
if tc.errorContains != "" {
assert.Contains(t, err.Error(), tc.errorContains)
}
} else {
assert.NoError(t, err)
}
})
}
}
func TestGetAllowedStorageDirectory(t *testing.T) {
allowedDir := getAllowedStorageDirectory()
if runtime.GOOS == "windows" {
// On Windows, should return %LOCALAPPDATA%\nrdot-collector\
assert.Contains(t, allowedDir, "nrdot-collector")
assert.True(t, filepath.IsAbs(allowedDir), "Windows path should be absolute")
assert.NotEmpty(t, allowedDir, "Windows path should not be empty")
} else {
// On Linux/Unix, should return /var/lib/nrdot-collector/
assert.Equal(t, "/var/lib/nrdot-collector/", allowedDir)
}
}
func TestConfigValidation_EnableStorage(t *testing.T) {
tests := []struct {
name string
config *Config
expectError bool
description string
}{
{
name: "storage enabled (default)",
config: &Config{
EnableStorage: nil, // nil means default (enabled)
},
expectError: false,
description: "Storage enabled by default should not error",
},
{
name: "storage explicitly enabled",
config: &Config{
EnableStorage: ptrBool(true),
},
expectError: false,
description: "Explicitly enabled storage should not error",
},
{
name: "storage disabled",
config: &Config{
EnableStorage: ptrBool(false),
},
expectError: false,
description: "Disabled storage should not error",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tc.config.Normalize()
err := tc.config.Validate()
if tc.expectError {
assert.Error(t, err, tc.description)
} else {
assert.NoError(t, err, tc.description)
}
})
}
}
func TestSymlinkAttackPrevention(t *testing.T) {
// Skip on Windows as symlinks require admin privileges
if runtime.GOOS == "windows" {
t.Skip("Skipping symlink tests on Windows")
}
// Create a temporary directory structure
tmpDir := t.TempDir()
baseDir := filepath.Join(tmpDir, "nrdot-collector")
err := os.MkdirAll(baseDir, 0o755)
require.NoError(t, err)
// Create a subdirectory
dataDir := filepath.Join(baseDir, "data")
err = os.MkdirAll(dataDir, 0o755)
require.NoError(t, err)
// Create malicious symlink pointing to /etc
maliciousSymlink := filepath.Join(dataDir, "evil_link")
err = os.Symlink("/etc", maliciousSymlink)
require.NoError(t, err)
// Try to use a path through the symlink
attackPath := filepath.Join(maliciousSymlink, "passwd")
err = checkPathForSymlinks(attackPath, baseDir)
assert.Error(t, err, "Attack path through symlink should be rejected")
assert.Contains(t, err.Error(), "is a symlink", "Error should mention symlink detection")
}
func TestPathTraversalPrevention(t *testing.T) {
// Test that path traversal is prevented by filepath.Clean
var traversalPath string
var expectedErrorSubstring string
if runtime.GOOS == "windows" {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
}
baseDir := filepath.Join(localAppData, "nrdot-collector")
traversalPath = filepath.Join(baseDir, "..", "..", "Windows", "System32", "config")
expectedErrorSubstring = "must be under"
} else {
traversalPath = "/var/lib/nrdot-collector/../../etc/passwd"
expectedErrorSubstring = "must be under /var/lib/nrdot-collector/"
}
err := validateStoragePath(traversalPath, nil)
assert.Error(t, err, "Path traversal should be rejected")
assert.Contains(t, err.Error(), expectedErrorSubstring)
}
func TestPathValidation_EdgeCases(t *testing.T) {
// Skip on macOS where /var is a symlink to /private/var
if runtime.GOOS == "darwin" {
t.Skip("Skipping Linux-specific path tests on macOS (where /var is a symlink)")
}
// Get platform-specific base path
var basePath string
if runtime.GOOS == "windows" {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
localAppData = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")
}
basePath = filepath.Join(localAppData, "nrdot-collector")
} else {
basePath = "/var/lib/nrdot-collector"
}
tests := []struct {
name string
storagePath string
expectError bool
errorContains string
}{
{
name: "path with trailing slash",
storagePath: filepath.Join(basePath, "state.db") + string(filepath.Separator),
expectError: false, // filepath.Clean will remove trailing slash
},
{
name: "path with dot",
storagePath: filepath.Join(basePath, ".", "state.db"),
expectError: false, // filepath.Clean handles this
},
}
// Add Linux-specific test for double slashes
if runtime.GOOS != "windows" {
tests = append(tests, struct {
name string
storagePath string
expectError bool
errorContains string
}{
name: "double slashes in path",
storagePath: "/var/lib/nrdot-collector//data//state.db",
expectError: false, // filepath.Clean handles this
})
}
// Add Windows-specific edge cases
if runtime.GOOS == "windows" {
windowsTests := []struct {
name string
storagePath string
expectError bool
errorContains string
}{
{
name: "Windows path with forward slashes",
storagePath: basePath + "/data/state.db",
expectError: false, // filepath.Clean handles mixed separators
},
{
name: "Windows path with mixed separators",
storagePath: basePath + "\\data/subdir\\state.db",
expectError: false, // filepath.Clean normalizes this
},
}
tests = append(tests, windowsTests...)
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := validateStoragePath(tc.storagePath, nil)
if tc.expectError {
assert.Error(t, err)
if tc.errorContains != "" {
assert.Contains(t, err.Error(), tc.errorContains)
}
} else {
assert.NoError(t, err)
}
})
}
}
// TestTOCTOUProtection verifies that symlinks are re-validated immediately before write operations
// to prevent Time-of-Check to Time-of-Use (TOCTOU) race conditions
func TestTOCTOUProtection(t *testing.T) {
// Skip on Windows as symlinks require admin privileges
if runtime.GOOS == "windows" {
t.Skip("Skipping symlink tests on Windows")
}
// Create a temporary directory structure
tmpDir := t.TempDir()
baseDir := filepath.Join(tmpDir, "nrdot-collector")
err := os.MkdirAll(baseDir, 0o755)
require.NoError(t, err)
dataDir := filepath.Join(baseDir, "data")
err = os.MkdirAll(dataDir, 0o755)
require.NoError(t, err)
// Create a legitimate file path initially
filePath := filepath.Join(dataDir, "test.db")
// Create storage with the valid path
storage := newFileStorageForTesting(filePath, baseDir)
// Write initial data successfully
testEntities := map[string]*trackedEntity{
"entity1": {
Identity: "entity1",
CurrentValues: map[string]float64{"metric1": 10.5},
},
}
err = storage.Save(testEntities)
require.NoError(t, err, "Initial save should succeed")
// Now simulate a TOCTOU attack: replace data directory with a symlink to /tmp
// First remove the existing data directory and file
err = os.RemoveAll(dataDir)
require.NoError(t, err)
// Create a symlink in its place pointing to /tmp
err = os.Symlink("/tmp", dataDir)
require.NoError(t, err)
// Try to write again - this should fail because symlink is re-validated before write
err = storage.Save(testEntities)
assert.Error(t, err, "Save should fail when directory is replaced with symlink")
assert.Contains(t, err.Error(), "symlink validation failed before write", "Error should mention validation failure")
assert.Contains(t, err.Error(), "is a symlink", "Error should mention symlink detection")
// Verify that no file was written to /tmp
tmpFilePath := filepath.Join("/tmp", "test.db")
_, err = os.Stat(tmpFilePath)
assert.True(t, os.IsNotExist(err), "File should not be written to /tmp through symlink")
}
// TestPermissionErrorHandling verifies that permission errors during symlink validation
// do not silently bypass security checks
func TestPermissionErrorHandling(t *testing.T) {
// Skip on Windows as permission handling differs significantly
if runtime.GOOS == "windows" {
t.Skip("Skipping permission tests on Windows")
}
// This test verifies the fix for: "Permission errors can silently bypass the symlink protection"
// We ensure that if we can't verify a path isn't a symlink due to permission errors,
// we reject it rather than allowing it
// Create a temporary directory structure
tmpDir := t.TempDir()
baseDir := filepath.Join(tmpDir, "nrdot-collector")
err := os.MkdirAll(baseDir, 0o755)
require.NoError(t, err)
// Create a directory that we'll make unreadable
restrictedDir := filepath.Join(baseDir, "restricted")
err = os.MkdirAll(restrictedDir, 0o755)
require.NoError(t, err)
// Create a file inside it
testFile := filepath.Join(restrictedDir, "test.db")
err = os.WriteFile(testFile, []byte("test"), 0o600)
require.NoError(t, err)
// Make the directory unreadable (no execute permission means we can't access contents)
err = os.Chmod(restrictedDir, 0o000)
require.NoError(t, err)
// Ensure we restore permissions after test
defer func() {
_ = os.Chmod(restrictedDir, 0o755)
}()
// Try to validate the path - should fail due to permission error, not silently pass
err = checkPathForSymlinks(testFile, baseDir)
assert.Error(t, err, "checkPathForSymlinks should fail when it can't verify path security")
assert.Contains(t, err.Error(), "cannot verify path security", "Error should indicate inability to verify")
}