-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsecurity_test.go
More file actions
984 lines (821 loc) · 29.6 KB
/
security_test.go
File metadata and controls
984 lines (821 loc) · 29.6 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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
package main
import (
"archive/zip"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/wanetty/upgopher/internal/handlers"
"github.com/wanetty/upgopher/internal/security"
)
// TestPathTraversalAttacks tests various path traversal attack vectors
func TestPathTraversalAttacks(t *testing.T) {
tempDir := t.TempDir()
attacks := []struct {
name string
attackPath string
description string
}{
{
name: "classic dot-dot-slash",
attackPath: "../../../etc/passwd",
description: "Classic path traversal using ../",
},
{
name: "encoded dot-dot-slash",
attackPath: "..%2F..%2F..%2Fetc%2Fpasswd",
description: "URL-encoded path traversal",
},
{
name: "double encoded",
attackPath: "..%252F..%252F..%252Fetc%252Fpasswd",
description: "Double URL-encoded path traversal",
},
{
name: "backslash variant",
attackPath: "..\\..\\..\\etc\\passwd",
description: "Windows-style path traversal",
},
{
name: "absolute path",
attackPath: "/etc/passwd",
description: "Absolute path escape attempt",
},
{
name: "null byte injection",
attackPath: "file.txt\x00../../etc/passwd",
description: "Null byte path traversal",
},
}
for _, att := range attacks {
t.Run(att.name, func(t *testing.T) {
// Try to construct a path with the attack vector
// Note: filepath.Join automatically cleans many attack vectors
attackFullPath := filepath.Join(tempDir, att.attackPath)
// IsSafePath should detect this
safe, err := security.IsSafePath(tempDir, attackFullPath)
if err != nil {
// Error is acceptable for malformed paths
t.Logf("Attack '%s' caused error (blocked): %v", att.name, err)
return
}
if safe {
// A "safe" result is only acceptable if filepath.Join already normalized
// the attack into a path still within tempDir.
resolvedWithinBase := strings.HasPrefix(attackFullPath, tempDir+string(filepath.Separator)) || attackFullPath == tempDir
if resolvedWithinBase {
t.Logf("Attack '%s' was neutralized by filepath.Join normalization", att.name)
} else {
t.Errorf("Attack '%s' escaped base directory: IsSafePath returned safe=true for path outside baseDir: %s", att.name, attackFullPath)
}
} else {
t.Logf("Attack '%s' successfully blocked", att.name)
}
})
}
}
// TestDirectoryDeletionPrevention tests that directories cannot be deleted
func TestDirectoryDeletionPrevention(t *testing.T) {
tempDir := t.TempDir()
testSubDir := filepath.Join(tempDir, "testdir")
err := os.Mkdir(testSubDir, 0755)
if err != nil {
t.Fatalf("Failed to create test directory: %v", err)
}
// Create a file inside to make it non-empty
testFile := filepath.Join(testSubDir, "file.txt")
err = os.WriteFile(testFile, []byte("test"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
encodedPath := base64.StdEncoding.EncodeToString([]byte("testdir"))
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Delete()
req := httptest.NewRequest("GET", "/delete/?path="+encodedPath, nil)
w := httptest.NewRecorder()
handler(w, req)
// Should return 403 Forbidden because directory is not empty
if w.Code != http.StatusForbidden {
t.Errorf("Expected status 403 Forbidden, got %d", w.Code)
}
// Verify directory still exists
if _, err := os.Stat(testSubDir); os.IsNotExist(err) {
t.Error("Directory was deleted despite protection!")
}
// Verify body contains appropriate error message
if !strings.Contains(w.Body.String(), "Directory is not empty") {
t.Errorf("Expected error message about non-empty directory, got: %s", w.Body.String())
}
}
// TestDeleteEmptyDirectory tests that empty directories can be deleted
func TestDeleteEmptyDirectory(t *testing.T) {
tempDir := t.TempDir()
emptyDir := filepath.Join(tempDir, "emptydir")
if err := os.Mkdir(emptyDir, 0755); err != nil {
t.Fatalf("Failed to create empty test directory: %v", err)
}
encodedPath := base64.StdEncoding.EncodeToString([]byte("emptydir"))
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Delete()
req := httptest.NewRequest("GET", "/delete/?path="+encodedPath, nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusSeeOther {
t.Errorf("Expected redirect (303) after deleting empty dir, got %d: %s", w.Code, w.Body.String())
}
if _, err := os.Stat(emptyDir); !os.IsNotExist(err) {
t.Error("Empty directory was not deleted")
}
}
// TestDeleteDirectoryReadOnly tests that directories cannot be deleted in readonly mode
func TestDeleteDirectoryReadOnly(t *testing.T) {
tempDir := t.TempDir()
emptyDir := filepath.Join(tempDir, "emptydir")
if err := os.Mkdir(emptyDir, 0755); err != nil {
t.Fatalf("Failed to create empty test directory: %v", err)
}
encodedPath := base64.StdEncoding.EncodeToString([]byte("emptydir"))
fh := handlers.NewFileHandlers(tempDir, true, false, true, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Delete()
req := httptest.NewRequest("GET", "/delete/?path="+encodedPath, nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("Expected 403 in readonly mode, got %d", w.Code)
}
if _, err := os.Stat(emptyDir); os.IsNotExist(err) {
t.Error("Directory was deleted in readonly mode!")
}
}
// TestMkdirHandler tests the Mkdir handler
func TestMkdirHandler(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Mkdir()
tests := []struct {
name string
folderName string
currentPath string
expectedStatus int
shouldExist bool
}{
{
name: "valid folder at root",
folderName: "new-folder",
currentPath: "",
expectedStatus: http.StatusCreated,
shouldExist: true,
},
{
name: "valid folder with underscores",
folderName: "my_folder_123",
currentPath: "",
expectedStatus: http.StatusCreated,
shouldExist: true,
},
{
name: "invalid name with spaces",
folderName: "my folder",
currentPath: "",
expectedStatus: http.StatusBadRequest,
shouldExist: false,
},
{
name: "invalid name with slash",
folderName: "sub/folder",
currentPath: "",
expectedStatus: http.StatusBadRequest,
shouldExist: false,
},
{
name: "empty folder name",
folderName: "",
currentPath: "",
expectedStatus: http.StatusBadRequest,
shouldExist: false,
},
{
name: "path traversal attempt via folderName",
folderName: "../escape",
currentPath: "",
expectedStatus: http.StatusBadRequest,
shouldExist: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := "folderName=" + tt.folderName + "¤tPath=" + tt.currentPath
req := httptest.NewRequest("POST", "/mkdir", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d: %s", tt.expectedStatus, w.Code, w.Body.String())
}
// Skip existence check for empty/special folder names where filepath.Join
// would resolve to an existing directory (e.g. tempDir itself).
if tt.folderName == "" || strings.ContainsAny(tt.folderName, "/\\") {
return
}
expectedPath := filepath.Join(tempDir, tt.folderName)
_, statErr := os.Stat(expectedPath)
exists := !os.IsNotExist(statErr)
if exists != tt.shouldExist {
t.Errorf("Folder existence mismatch: shouldExist=%v, exists=%v", tt.shouldExist, exists)
}
})
}
}
// TestMkdirReadOnly tests that Mkdir is blocked in readonly mode
func TestMkdirReadOnly(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, true, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Mkdir()
body := "folderName=test-folder¤tPath="
req := httptest.NewRequest("POST", "/mkdir", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("Expected 403 in readonly mode, got %d", w.Code)
}
if _, err := os.Stat(filepath.Join(tempDir, "test-folder")); !os.IsNotExist(err) {
t.Error("Folder was created in readonly mode!")
}
}
// TestMkdirPathTraversal tests path traversal attacks via currentPath
func TestMkdirPathTraversal(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Mkdir()
attacks := []string{
base64.StdEncoding.EncodeToString([]byte("../../")),
base64.StdEncoding.EncodeToString([]byte("../outside")),
base64.StdEncoding.EncodeToString([]byte("/etc")),
}
for _, encodedAttack := range attacks {
t.Run("attack_"+encodedAttack[:8], func(t *testing.T) {
body := "folderName=evil¤tPath=" + encodedAttack
req := httptest.NewRequest("POST", "/mkdir", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
handler(w, req)
if w.Code == http.StatusCreated {
t.Errorf("Path traversal via currentPath was not blocked (status %d)", w.Code)
}
// Verify no folder was created outside tempDir
parentDir := filepath.Dir(tempDir)
evilPath := filepath.Join(parentDir, "evil")
if _, err := os.Stat(evilPath); !os.IsNotExist(err) {
t.Errorf("Folder was created outside base directory: %s", evilPath)
os.Remove(evilPath)
}
})
}
}
// TestMkdirDuplicate tests creating a folder that already exists
func TestMkdirDuplicate(t *testing.T) {
tempDir := t.TempDir()
if err := os.Mkdir(filepath.Join(tempDir, "existing"), 0755); err != nil {
t.Fatalf("Failed to create existing dir: %v", err)
}
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Mkdir()
body := "folderName=existing¤tPath="
req := httptest.NewRequest("POST", "/mkdir", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusConflict {
t.Errorf("Expected 409 Conflict for duplicate folder, got %d", w.Code)
}
}
// TestMkdirMethodNotAllowed tests that GET requests are rejected
func TestMkdirMethodNotAllowed(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Mkdir()
req := httptest.NewRequest("GET", "/mkdir?folderName=test", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("Expected 405 for GET on /mkdir, got %d", w.Code)
}
}
// TestRateLimitingSequential tests rate limiting with sequential requests
func TestRateLimitingSequential(t *testing.T) {
// Use unique IP for this test
testIP := "sequential.test.192.168.1.50"
successCount := 0
blockedCount := 0
// Send 25 sequential requests (should allow 20, block 5)
for i := 0; i < 25; i++ {
allowed := security.CheckRateLimit(testIP)
if allowed {
successCount++
} else {
blockedCount++
}
}
t.Logf("Rate limiting results: %d allowed, %d blocked", successCount, blockedCount)
// Should have exactly 20 allowed and 5 blocked
if successCount != 20 {
t.Errorf("Expected 20 successful requests, got %d", successCount)
}
if blockedCount != 5 {
t.Errorf("Expected 5 blocked requests, got %d", blockedCount)
}
}
// TestCustomPathsConcurrentAccess tests concurrent access to custom paths map
func TestCustomPathsConcurrentAccess(t *testing.T) {
tempDir := t.TempDir()
// Create test files
for i := 0; i < 10; i++ {
filename := fmt.Sprintf("file%d.txt", i)
filepath := filepath.Join(tempDir, filename)
err := os.WriteFile(filepath, []byte("test"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
}
cph := handlers.NewCustomPathHandler(tempDir, true, &customPaths, &customPathsMutex)
handler := cph.Handle()
var wg sync.WaitGroup
errors := make(chan error, 100)
// Concurrent writes to custom paths
for i := 0; i < 50; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
fileNum := index % 10
originalPath := fmt.Sprintf("file%d.txt", fileNum)
customPath := fmt.Sprintf("custom-%d-%d", fileNum, index)
// Create POST request
body := fmt.Sprintf("originalPath=%s&customPath=%s", originalPath, customPath)
req := httptest.NewRequest("POST", "/custom-path", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
handler(w, req)
// Check for data races or unexpected errors
// Status codes: 200 OK (old behavior), 303 SeeOther (redirect after creation), 409 Conflict
if w.Code != http.StatusOK && w.Code != http.StatusConflict && w.Code != http.StatusSeeOther {
errors <- fmt.Errorf("unexpected status code: %d", w.Code)
}
}(i)
}
wg.Wait()
close(errors)
// Check for errors
errorCount := 0
for err := range errors {
t.Logf("Concurrent access error: %v", err)
errorCount++
}
if errorCount > 0 {
t.Errorf("Got %d errors during concurrent custom path access", errorCount)
}
}
// TestRawHandlerPathSecurity tests raw file handler against path traversal
func TestRawHandlerPathSecurity(t *testing.T) {
tempDir := t.TempDir()
// Create a safe file
testFile := filepath.Join(tempDir, "safe.txt")
err := os.WriteFile(testFile, []byte("safe content"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Raw()
attacks := []string{
"../../../etc/passwd",
"..%2F..%2Fetc%2Fpasswd",
"/etc/passwd",
"safe.txt/../../etc/passwd",
}
for _, attack := range attacks {
t.Run("attack_"+attack, func(t *testing.T) {
req := httptest.NewRequest("GET", "/raw/"+attack, nil)
w := httptest.NewRecorder()
handler(w, req)
// Should return 403 or 404, not 200
if w.Code == http.StatusOK {
t.Errorf("Path traversal attack succeeded with path: %s", attack)
}
// Should not return sensitive content
body := w.Body.String()
if strings.Contains(body, "root:") || strings.Contains(body, "/bin/bash") {
t.Errorf("Sensitive file content leaked via path traversal!")
}
})
}
}
// TestClipboardRateLimitRecovery tests that rate limit resets after time window
func TestClipboardRateLimitRecovery(t *testing.T) {
if testing.Short() {
t.Skip("Skipping time-based test in short mode")
}
testIP := "recovery.test.192.168.1.75"
// Fill up the rate limit
for i := 0; i < 20; i++ {
security.CheckRateLimit(testIP)
}
// 21st request should be blocked
if security.CheckRateLimit(testIP) {
t.Error("Expected rate limit to be exhausted")
}
// Wait for rate limit window to pass (slightly over 1 minute)
t.Log("Waiting for rate limit window to reset (65 seconds)...")
time.Sleep(65 * time.Second)
// Should be able to make requests again (?tab=default route)
if !security.CheckRateLimit(testIP) {
t.Error("Rate limit should have reset after time window")
}
}
// TestSearchHandlerPathSecurity tests search endpoint against path injection
func TestSearchHandlerPathSecurity(t *testing.T) {
tempDir := t.TempDir()
// Create a test file
testFile := filepath.Join(tempDir, "searchable.txt")
err := os.WriteFile(testFile, []byte("searchable content"), 0644)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Search()
// Attempt path traversal via search
encodedAttack := base64.StdEncoding.EncodeToString([]byte("../../../etc/passwd"))
req := httptest.NewRequest("GET",
fmt.Sprintf("/search-file?path=%s&term=root&caseSensitive=false&wholeWord=false", encodedAttack),
nil)
w := httptest.NewRecorder()
handler(w, req)
// Should return 403 Forbidden, not search results
if w.Code == http.StatusOK {
t.Error("Path traversal in search handler was not blocked")
}
if w.Code != http.StatusForbidden && w.Code != http.StatusNotFound {
t.Errorf("Expected 403 or 404, got %d", w.Code)
}
}
// TestUploadPathTraversal tests that uploaded filenames cannot escape the upload directory
func TestUploadPathTraversal(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.List()
maliciousName := "../../outside.txt"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", maliciousName)
if err != nil {
t.Fatalf("Failed to create form file: %v", err)
}
_, _ = part.Write([]byte("malicious content"))
writer.Close()
req := httptest.NewRequest("POST", "/", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
w := httptest.NewRecorder()
handler(w, req)
// The file must NOT have been created at the traversal path outside tempDir
escapedPath := filepath.Clean(filepath.Join(tempDir, maliciousName))
if !strings.HasPrefix(escapedPath, tempDir) {
if _, statErr := os.Stat(escapedPath); !os.IsNotExist(statErr) {
t.Errorf("Path traversal upload succeeded: file created outside upload dir at %s", escapedPath)
}
}
}
// TestZipPathTraversal tests that the zip endpoint cannot traverse outside the base directory
func TestZipPathTraversal(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.Zip()
encodedMalicious := base64.StdEncoding.EncodeToString([]byte("../../"))
req := httptest.NewRequest("GET", "/zip?path="+encodedMalicious, nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("Zip path traversal should return 403 Forbidden, got %d", w.Code)
}
}
func TestZipSelectedInvalidPathEncoding(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.ZipSelected()
body, err := json.Marshal(map[string][]string{"paths": {"%%%"}})
if err != nil {
t.Fatalf("failed to marshal request body: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/zip-selected", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for invalid base64 path, got %d", w.Code)
}
}
func TestZipSelectedPathTraversal(t *testing.T) {
tempDir := t.TempDir()
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.ZipSelected()
malicious := base64.StdEncoding.EncodeToString([]byte("../../"))
body, err := json.Marshal(map[string][]string{"paths": {malicious}})
if err != nil {
t.Fatalf("failed to marshal request body: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/zip-selected", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403 for path traversal, got %d", w.Code)
}
}
func TestZipSelectedWithDirectoryAndDedup(t *testing.T) {
tempDir := t.TempDir()
treeDir := filepath.Join(tempDir, "tree")
emptyDir := filepath.Join(treeDir, "empty")
nestedDir := filepath.Join(treeDir, "nested")
if err := os.MkdirAll(emptyDir, 0755); err != nil {
t.Fatalf("failed to create empty dir: %v", err)
}
if err := os.MkdirAll(nestedDir, 0755); err != nil {
t.Fatalf("failed to create nested dir: %v", err)
}
nestedFile := filepath.Join(nestedDir, "hello.txt")
if err := os.WriteFile(nestedFile, []byte("hello world"), 0644); err != nil {
t.Fatalf("failed to create nested file: %v", err)
}
standalone := filepath.Join(tempDir, "single.txt")
if err := os.WriteFile(standalone, []byte("single"), 0644); err != nil {
t.Fatalf("failed to create standalone file: %v", err)
}
treePath := base64.StdEncoding.EncodeToString([]byte("tree"))
nestedFilePath := base64.StdEncoding.EncodeToString([]byte(filepath.ToSlash(filepath.Join("tree", "nested", "hello.txt"))))
standalonePath := base64.StdEncoding.EncodeToString([]byte("single.txt"))
fh := handlers.NewFileHandlers(tempDir, true, false, false, 0, &showHiddenFiles, &customPaths, &customPathsMutex)
handler := fh.ZipSelected()
body, err := json.Marshal(map[string][]string{"paths": {treePath, nestedFilePath, standalonePath}})
if err != nil {
t.Fatalf("failed to marshal request body: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/zip-selected", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for valid mixed selection, got %d: %s", w.Code, w.Body.String())
}
entries := readZipEntries(t, w.Body.Bytes())
if entries["tree/"] != 1 {
t.Fatalf("expected tree/ directory entry to exist once, got %d", entries["tree/"])
}
if entries["tree/empty/"] != 1 {
t.Fatalf("expected empty directory entry to exist once, got %d", entries["tree/empty/"])
}
if entries["tree/nested/"] != 1 {
t.Fatalf("expected nested directory entry to exist once, got %d", entries["tree/nested/"])
}
if entries["tree/nested/hello.txt"] != 1 {
t.Fatalf("expected nested file to be deduplicated to one entry, got %d", entries["tree/nested/hello.txt"])
}
if entries["single.txt"] != 1 {
t.Fatalf("expected standalone file entry to exist once, got %d", entries["single.txt"])
}
}
func readZipEntries(t *testing.T, body []byte) map[string]int {
t.Helper()
zipBytes, err := io.ReadAll(bytes.NewReader(body))
if err != nil {
t.Fatalf("failed to read zip body: %v", err)
}
r, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
if err != nil {
t.Fatalf("failed to open zip response: %v", err)
}
entries := make(map[string]int)
for _, f := range r.File {
entries[f.Name]++
}
return entries
}
// TestClipboardTabNameInjection tests that malicious tab names are rejected by the handler.
func TestClipboardTabNameInjection(t *testing.T) {
ch := handlers.NewClipboardHandler(true, 20)
handle := ch.Handle()
attacks := []struct {
name string
tabName string
}{
{"xss script tag", "<script>alert(1)</script>"},
{"xss img onerror", `<img src=x onerror=alert(1)>`},
{"path traversal", "../../../etc/passwd"},
{"sql injection", "'; DROP TABLE tabs;--"},
{"null byte", "tab\x00name"},
{"long name", strings.Repeat("a", 200)},
{"unicode bypass", "\u003cscript\u003e"},
{"shell injection", "$(rm -rf /)"},
}
for _, att := range attacks {
t.Run(att.name, func(t *testing.T) {
// url.Values ensures the name is percent-encoded so httptest.NewRequest
// doesn't panic; the server decodes it before regex validation.
params := url.Values{"tab": {att.tabName}}
req := httptest.NewRequest("POST", "/clipboard?"+params.Encode(), strings.NewReader("x"))
req.RemoteAddr = "192.168.0.1:11111"
w := httptest.NewRecorder()
handle(w, req)
if w.Code == http.StatusOK {
t.Errorf("injection attack %q was accepted (expected 400)", att.name)
}
})
}
}
// TestClipboardMaxTabsExhaustion tests exhaustion with maxTabs+1 creates from concurrent goroutines.
func TestClipboardMaxTabsExhaustion(t *testing.T) {
const maxTabs = 5
ch := handlers.NewClipboardHandler(true, maxTabs)
handle := ch.Handle()
// Create maxTabs-1 extra tabs (default already occupies 1 slot)
for i := 0; i < maxTabs-1; i++ {
name := fmt.Sprintf("tab%d", i)
req := httptest.NewRequest("POST", "/clipboard?tab="+name, strings.NewReader("x"))
req.RemoteAddr = "10.1.0.1:9999"
w := httptest.NewRecorder()
handle(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("creating %q: expected 201, got %d: %s", name, w.Code, w.Body.String())
}
}
// Next create must hit the cap
req := httptest.NewRequest("POST", "/clipboard?tab=overflow", strings.NewReader("x"))
req.RemoteAddr = "10.1.0.1:9999"
w := httptest.NewRecorder()
handle(w, req)
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 at maxTabs cap, got %d: %s", w.Code, w.Body.String())
}
}
// TestClipboardConcurrentTabCreation races concurrent goroutines each creating a unique tab.
func TestClipboardConcurrentTabCreation(t *testing.T) {
ch := handlers.NewClipboardHandler(true, 100)
handle := ch.Handle()
var wg sync.WaitGroup
for i := 0; i < 30; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
name := fmt.Sprintf("concurrent-%d", n)
req := httptest.NewRequest("POST", "/clipboard?tab="+name, strings.NewReader("data"))
req.RemoteAddr = fmt.Sprintf("10.2.0.%d:8080", n%254+1)
w := httptest.NewRecorder()
handle(w, req)
}(i)
}
wg.Wait()
// Verify all tabs are accessible without panic
req := httptest.NewRequest("GET", "/clipboard/tabs", nil)
w := httptest.NewRecorder()
ch.ListTabs()(w, req)
if w.Code != http.StatusOK {
t.Errorf("ListTabs after concurrent writes: expected 200, got %d", w.Code)
}
}
// TestClipboardTokenTimingAttack verifies that wrong-token responses take roughly
// the same time as correct-token responses (constant-time compare).
func TestClipboardTokenTimingAttack(t *testing.T) {
if testing.Short() {
t.Skip("Skipping timing-sensitive test in short mode")
}
const iterations = 500
ch := handlers.NewClipboardHandler(true, 10)
handle := ch.Handle()
// Create a protected tab and capture the token.
setupReq := httptest.NewRequest("POST", "/clipboard?tab=timing-test", strings.NewReader("x"))
setupReq.RemoteAddr = "127.0.0.1:10101"
setupReq.Header.Set("X-Tab-Token-Create", "1")
setupW := httptest.NewRecorder()
handle(setupW, setupReq)
if setupW.Code != 201 {
t.Fatalf("setup failed: %d", setupW.Code)
}
correctToken := setupW.Header().Get("X-Generated-Token")
wrongToken := strings.Repeat("b", 64)
measure := func(token string) time.Duration {
start := time.Now()
for i := 0; i < iterations; i++ {
req := httptest.NewRequest("GET", "/clipboard?tab=timing-test", nil)
req.Header.Set("X-Tab-Token", token)
w := httptest.NewRecorder()
handle(w, req)
}
return time.Since(start)
}
correctTime := measure(correctToken)
wrongTime := measure(wrongToken)
// Allow 10× variance — the constant-time compare itself is negligible vs HTTP overhead,
// but a timing leak would show orders-of-magnitude difference.
ratio := float64(correctTime) / float64(wrongTime)
if ratio > 10 || ratio < 0.1 {
t.Errorf("timing ratio correct/wrong = %.2f — potential timing leak", ratio)
}
}
// TestClipboardTokenOversizedInput verifies that a very long token header does not panic.
func TestClipboardTokenOversizedInput(t *testing.T) {
ch := handlers.NewClipboardHandler(true, 10)
handle := ch.Handle()
// Create a protected tab.
setupReq := httptest.NewRequest("POST", "/clipboard?tab=oversize", strings.NewReader("x"))
setupReq.RemoteAddr = "127.0.0.1:10202"
setupReq.Header.Set("X-Tab-Token-Create", "1")
setupW := httptest.NewRecorder()
handle(setupW, setupReq)
if setupW.Code != 201 {
t.Fatalf("setup failed: %d", setupW.Code)
}
// Send a 1 MB token header — must return 401 cleanly, not panic.
req := httptest.NewRequest("GET", "/clipboard?tab=oversize", nil)
req.Header.Set("X-Tab-Token", strings.Repeat("a", 1<<20))
w := httptest.NewRecorder()
handle(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("expected 401 for oversized token, got %d", w.Code)
}
}
// TestBasicAuthBypass tests that authentication cannot be bypassed
func TestBasicAuthBypass(t *testing.T) {
username := "testuser"
password := "testpass"
// Create a simple handler
protectedHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Protected content"))
}
// Wrap with basic auth
authHandler := security.ApplyBasicAuth(protectedHandler, username, password)
tests := []struct {
name string
username string
password string
expectedStatus int
}{
{
name: "valid credentials",
username: "testuser",
password: "testpass",
expectedStatus: http.StatusOK,
},
{
name: "wrong password",
username: "testuser",
password: "wrongpass",
expectedStatus: http.StatusUnauthorized,
},
{
name: "wrong username",
username: "wronguser",
password: "testpass",
expectedStatus: http.StatusUnauthorized,
},
{
name: "no credentials",
username: "",
password: "",
expectedStatus: http.StatusUnauthorized,
},
{
name: "timing attack protection",
username: "testuse", // One char short
password: "testpass",
expectedStatus: http.StatusUnauthorized,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
if tt.username != "" || tt.password != "" {
req.SetBasicAuth(tt.username, tt.password)
}
w := httptest.NewRecorder()
authHandler(w, req)
if w.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, w.Code)
}
if tt.expectedStatus == http.StatusUnauthorized {
// Verify WWW-Authenticate header is present
if w.Header().Get("WWW-Authenticate") == "" {
t.Error("Missing WWW-Authenticate header")
}
}
})
}
}