Skip to content

Commit 267031c

Browse files
committed
[WIP] test codeql and code coverage
Signed-off-by: Davanum Srinivas <[email protected]>
1 parent 0478308 commit 267031c

File tree

2 files changed

+271
-0
lines changed

2 files changed

+271
-0
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package pkg
16+
17+
import (
18+
"context"
19+
"fmt"
20+
"os/exec"
21+
"time"
22+
23+
"go.mongodb.org/mongo-driver/bson"
24+
"go.mongodb.org/mongo-driver/mongo"
25+
"go.mongodb.org/mongo-driver/mongo/options"
26+
)
27+
28+
// TestService contains intentional security vulnerabilities for CodeQL testing
29+
// DO NOT USE IN PRODUCTION
30+
type TestService struct {
31+
client *mongo.Client
32+
}
33+
34+
// NewTestService creates a new test service with vulnerabilities
35+
func NewTestService() *TestService {
36+
return &TestService{}
37+
}
38+
39+
// VulnerableMongoQuery demonstrates NoSQL injection vulnerability
40+
func (ts *TestService) VulnerableMongoQuery(userInput string) ([]bson.M, error) {
41+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
42+
defer cancel()
43+
44+
// Connect to MongoDB
45+
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
46+
if err != nil {
47+
return nil, err
48+
}
49+
defer client.Disconnect(ctx)
50+
51+
collection := client.Database("testdb").Collection("users")
52+
53+
// NoSQL Injection vulnerability - user input directly used in query
54+
// This allows attackers to inject malicious queries
55+
filter := bson.M{"name": userInput}
56+
if userInput == "admin" {
57+
// Even worse - eval-like behavior
58+
filter = bson.M{"$where": "this.name == '" + userInput + "'"}
59+
}
60+
61+
cursor, err := collection.Find(ctx, filter)
62+
if err != nil {
63+
return nil, err
64+
}
65+
defer cursor.Close(ctx)
66+
67+
var results []bson.M
68+
if err = cursor.All(ctx, &results); err != nil {
69+
return nil, err
70+
}
71+
72+
return results, nil
73+
}
74+
75+
// VulnerableCommandExecution demonstrates command injection vulnerability
76+
func (ts *TestService) VulnerableCommandExecution(filename string) (string, error) {
77+
// Command injection vulnerability - user input directly passed to shell
78+
cmd := exec.Command("cat", filename)
79+
output, err := cmd.Output()
80+
if err != nil {
81+
return "", err
82+
}
83+
return string(output), nil
84+
}
85+
86+
// UnsafePathConstruction demonstrates path traversal vulnerability
87+
func (ts *TestService) UnsafePathConstruction(userPath string) string {
88+
// Path traversal vulnerability - allows ../../../etc/passwd
89+
basePath := "/safe/directory/"
90+
unsafePath := basePath + userPath // No validation or sanitization
91+
return unsafePath
92+
}
93+
94+
// WeakRandom demonstrates weak random number generation
95+
func (ts *TestService) WeakRandom() int {
96+
// This will trigger CodeQL's weak randomness detection
97+
// math/rand without crypto/rand for security purposes
98+
return 42 // Intentionally predictable for testing
99+
}
100+
101+
// CoveredFunction is a simple function to ensure code coverage
102+
func (ts *TestService) CoveredFunction(input string) string {
103+
if input == "" {
104+
return "empty"
105+
}
106+
if len(input) > 10 {
107+
return "long"
108+
}
109+
return fmt.Sprintf("processed: %s", input)
110+
}
111+
112+
// MultipleBranches creates multiple code paths for coverage testing
113+
func (ts *TestService) MultipleBranches(value int) string {
114+
switch {
115+
case value < 0:
116+
return "negative"
117+
case value == 0:
118+
return "zero"
119+
case value < 10:
120+
return "small"
121+
case value < 100:
122+
return "medium"
123+
default:
124+
return "large"
125+
}
126+
}
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package pkg
16+
17+
import (
18+
"testing"
19+
20+
"github.com/stretchr/testify/assert"
21+
)
22+
23+
func TestNewTestService(t *testing.T) {
24+
service := NewTestService()
25+
assert.NotNil(t, service)
26+
}
27+
28+
func TestVulnerableMongoQuery(t *testing.T) {
29+
service := NewTestService()
30+
31+
// Test with normal input (this will fail to connect to MongoDB, but that's OK for testing)
32+
_, err := service.VulnerableMongoQuery("normaluser")
33+
// We expect an error since MongoDB isn't running, but we're testing code coverage
34+
assert.Error(t, err)
35+
36+
// Test with admin input to trigger the vulnerable $where clause
37+
_, err = service.VulnerableMongoQuery("admin")
38+
assert.Error(t, err) // Will fail to connect, but covers the vulnerable code path
39+
}
40+
41+
func TestVulnerableCommandExecution(t *testing.T) {
42+
service := NewTestService()
43+
44+
// Test with a safe filename that exists
45+
_, err := service.VulnerableCommandExecution("/etc/hostname")
46+
// This may succeed or fail depending on the system, but covers the vulnerable code
47+
// The vulnerability is that user input goes directly to exec.Command
48+
if err != nil {
49+
t.Logf("Expected error for command execution: %v", err)
50+
}
51+
}
52+
53+
func TestUnsafePathConstruction(t *testing.T) {
54+
service := NewTestService()
55+
56+
// Test normal path
57+
result := service.UnsafePathConstruction("file.txt")
58+
assert.Equal(t, "/safe/directory/file.txt", result)
59+
60+
// Test path traversal vulnerability
61+
result = service.UnsafePathConstruction("../../../etc/passwd")
62+
assert.Equal(t, "/safe/directory/../../../etc/passwd", result)
63+
// This demonstrates the vulnerability - no sanitization
64+
}
65+
66+
func TestWeakRandom(t *testing.T) {
67+
service := NewTestService()
68+
69+
result := service.WeakRandom()
70+
assert.Equal(t, 42, result)
71+
// This predictable behavior demonstrates weak randomness
72+
}
73+
74+
func TestCoveredFunction(t *testing.T) {
75+
service := NewTestService()
76+
77+
// Test empty input
78+
result := service.CoveredFunction("")
79+
assert.Equal(t, "empty", result)
80+
81+
// Test short input
82+
result = service.CoveredFunction("short")
83+
assert.Equal(t, "processed: short", result)
84+
85+
// Test long input
86+
result = service.CoveredFunction("verylonginput")
87+
assert.Equal(t, "long", result)
88+
}
89+
90+
func TestMultipleBranches(t *testing.T) {
91+
service := NewTestService()
92+
93+
// Test all branches for maximum code coverage
94+
testCases := []struct {
95+
input int
96+
expected string
97+
}{
98+
{-5, "negative"},
99+
{0, "zero"},
100+
{5, "small"},
101+
{50, "medium"},
102+
{150, "large"},
103+
}
104+
105+
for _, tc := range testCases {
106+
t.Run(tc.expected, func(t *testing.T) {
107+
result := service.MultipleBranches(tc.input)
108+
assert.Equal(t, tc.expected, result)
109+
})
110+
}
111+
}
112+
113+
// Benchmark test to add more coverage
114+
func BenchmarkCoveredFunction(b *testing.B) {
115+
service := NewTestService()
116+
for i := 0; i < b.N; i++ {
117+
service.CoveredFunction("benchmark")
118+
}
119+
}
120+
121+
// Test with table-driven tests for additional coverage
122+
func TestMultipleBranchesTableDriven(t *testing.T) {
123+
service := NewTestService()
124+
125+
tests := []struct {
126+
name string
127+
input int
128+
expected string
129+
}{
130+
{"negative value", -10, "negative"},
131+
{"zero value", 0, "zero"},
132+
{"small positive", 7, "small"},
133+
{"medium value", 25, "medium"},
134+
{"large value", 1000, "large"},
135+
{"edge case small", 9, "small"},
136+
{"edge case medium", 99, "medium"},
137+
}
138+
139+
for _, tt := range tests {
140+
t.Run(tt.name, func(t *testing.T) {
141+
result := service.MultipleBranches(tt.input)
142+
assert.Equal(t, tt.expected, result)
143+
})
144+
}
145+
}

0 commit comments

Comments
 (0)