Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/cmd/integration-test/integration-test.go
2070 views
1
package main
2
3
import (
4
"flag"
5
"fmt"
6
"os"
7
"regexp"
8
"runtime"
9
"strings"
10
11
"github.com/kitabisa/go-ci"
12
"github.com/logrusorgru/aurora"
13
14
"github.com/projectdiscovery/gologger"
15
"github.com/projectdiscovery/nuclei/v3/pkg/testutils"
16
"github.com/projectdiscovery/nuclei/v3/pkg/testutils/fuzzplayground"
17
sliceutil "github.com/projectdiscovery/utils/slice"
18
)
19
20
type TestCaseInfo struct {
21
Path string
22
TestCase testutils.TestCase
23
DisableOn func() bool
24
}
25
26
var (
27
debug = os.Getenv("DEBUG") == "true"
28
customTests = os.Getenv("TESTS")
29
protocol = os.Getenv("PROTO")
30
31
success = aurora.Green("[✓]").String()
32
failed = aurora.Red("[✘]").String()
33
34
protocolTests = map[string][]TestCaseInfo{
35
"http": httpTestcases,
36
"interactsh": interactshTestCases,
37
"network": networkTestcases,
38
"dns": dnsTestCases,
39
"workflow": workflowTestcases,
40
"loader": loaderTestcases,
41
"profile-loader": profileLoaderTestcases,
42
"websocket": websocketTestCases,
43
"headless": headlessTestcases,
44
"whois": whoisTestCases,
45
"ssl": sslTestcases,
46
"library": libraryTestcases,
47
"templatesPath": templatesPathTestCases,
48
"templatesDir": templatesDirTestCases,
49
"file": fileTestcases,
50
"offlineHttp": offlineHttpTestcases,
51
"customConfigDir": customConfigDirTestCases,
52
"fuzzing": fuzzingTestCases,
53
"code": codeTestCases,
54
"multi": multiProtoTestcases,
55
"generic": genericTestcases,
56
"dsl": dslTestcases,
57
"flow": flowTestcases,
58
"javascript": jsTestcases,
59
"matcher-status": matcherStatusTestcases,
60
"exporters": exportersTestCases,
61
}
62
// flakyTests are run with a retry count of 3
63
flakyTests = map[string]bool{
64
"protocols/http/self-contained-file-input.yaml": true,
65
}
66
67
// For debug purposes
68
runProtocol = ""
69
runTemplate = ""
70
extraArgs = []string{}
71
interactshRetryCount = 3
72
)
73
74
func main() {
75
flag.StringVar(&runProtocol, "protocol", "", "run integration tests of given protocol")
76
flag.StringVar(&runTemplate, "template", "", "run integration test of given template")
77
flag.Parse()
78
79
// allows passing extra args to nuclei
80
eargs := os.Getenv("DebugExtraArgs")
81
if eargs != "" {
82
extraArgs = strings.Split(eargs, " ")
83
testutils.ExtraDebugArgs = extraArgs
84
}
85
86
if runProtocol != "" {
87
debugTests()
88
os.Exit(1)
89
}
90
91
// start fuzz playground server
92
defer fuzzplayground.Cleanup()
93
server := fuzzplayground.GetPlaygroundServer()
94
defer func() {
95
_ = server.Close()
96
}()
97
go func() {
98
if err := server.Start("localhost:8082"); err != nil {
99
if !strings.Contains(err.Error(), "Server closed") {
100
gologger.Fatal().Msgf("Could not start server: %s\n", err)
101
}
102
}
103
}()
104
105
customTestsList := normalizeSplit(customTests)
106
107
failedTestTemplatePaths := runTests(customTestsList)
108
109
if len(failedTestTemplatePaths) > 0 {
110
if ci.IsCI() {
111
// run failed tests again assuming they are flaky
112
// if they fail as well only then we assume that there is an actual issue
113
fmt.Println("::group::Running failed tests again")
114
failedTestTemplatePaths = runTests(failedTestTemplatePaths)
115
fmt.Println("::endgroup::")
116
117
if len(failedTestTemplatePaths) > 0 {
118
debug = true
119
fmt.Println("::group::Failed integration tests in debug mode")
120
_ = runTests(failedTestTemplatePaths)
121
fmt.Println("::endgroup::")
122
} else {
123
fmt.Println("::group::All tests passed")
124
fmt.Println("::endgroup::")
125
os.Exit(0)
126
}
127
}
128
129
os.Exit(1)
130
}
131
}
132
133
// execute a testcase with retry and consider best of N
134
// intended for flaky tests like interactsh
135
func executeWithRetry(testCase testutils.TestCase, templatePath string, retryCount int) (string, error) {
136
var err error
137
for i := 0; i < retryCount; i++ {
138
err = testCase.Execute(templatePath)
139
if err == nil {
140
fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)
141
return "", nil
142
}
143
}
144
_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed after %v attempts : %s\n", failed, templatePath, retryCount, err)
145
return templatePath, err
146
}
147
148
func debugTests() {
149
testCaseInfos := protocolTests[runProtocol]
150
for _, testCaseInfo := range testCaseInfos {
151
if (runTemplate != "" && !strings.Contains(testCaseInfo.Path, runTemplate)) ||
152
(testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn()) {
153
continue
154
}
155
if runProtocol == "interactsh" {
156
if _, err := executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount); err != nil {
157
fmt.Printf("\n%v", err.Error())
158
}
159
} else {
160
if _, err := execute(testCaseInfo.TestCase, testCaseInfo.Path); err != nil {
161
fmt.Printf("\n%v", err.Error())
162
}
163
}
164
}
165
}
166
167
func runTests(customTemplatePaths []string) []string {
168
var failedTestTemplatePaths []string
169
170
for proto, testCaseInfos := range protocolTests {
171
if protocol != "" {
172
if !strings.EqualFold(proto, protocol) {
173
continue
174
}
175
}
176
if len(customTemplatePaths) == 0 {
177
fmt.Printf("Running test cases for %q protocol\n", aurora.Blue(proto))
178
}
179
for _, testCaseInfo := range testCaseInfos {
180
if testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn() {
181
fmt.Printf("skipping test case %v. disabled on %v.\n", aurora.Blue(testCaseInfo.Path), runtime.GOOS)
182
continue
183
}
184
if len(customTemplatePaths) == 0 || sliceutil.Contains(customTemplatePaths, testCaseInfo.Path) {
185
var failedTemplatePath string
186
var err error
187
if proto == "interactsh" || strings.Contains(testCaseInfo.Path, "interactsh") {
188
failedTemplatePath, err = executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount)
189
} else if flakyTests[testCaseInfo.Path] {
190
failedTemplatePath, err = executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount)
191
} else {
192
failedTemplatePath, err = execute(testCaseInfo.TestCase, testCaseInfo.Path)
193
}
194
if err != nil {
195
failedTestTemplatePaths = append(failedTestTemplatePaths, failedTemplatePath)
196
}
197
}
198
}
199
}
200
201
return failedTestTemplatePaths
202
}
203
204
func execute(testCase testutils.TestCase, templatePath string) (string, error) {
205
if err := testCase.Execute(templatePath); err != nil {
206
_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed: %s\n", failed, templatePath, err)
207
return templatePath, err
208
}
209
210
fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)
211
return "", nil
212
}
213
214
func expectResultsCount(results []string, expectedNumbers ...int) error {
215
results = filterLines(results)
216
match := sliceutil.Contains(expectedNumbers, len(results))
217
if !match {
218
return fmt.Errorf("incorrect number of results: %d (actual) vs %v (expected) \nResults:\n\t%s\n", len(results), expectedNumbers, strings.Join(results, "\n\t")) // nolint:all
219
}
220
return nil
221
}
222
223
func normalizeSplit(str string) []string {
224
return strings.FieldsFunc(str, func(r rune) bool {
225
return r == ','
226
})
227
}
228
229
// filterLines applies all filtering functions to the results
230
func filterLines(results []string) []string {
231
results = filterHeadlessLogs(results)
232
results = filterUnsignedTemplatesWarnings(results)
233
return results
234
}
235
236
// if chromium is not installed go-rod installs it in .cache directory
237
// this function filters out the logs from download and installation
238
func filterHeadlessLogs(results []string) []string {
239
// [launcher.Browser] 2021/09/23 15:24:05 [launcher] [info] Starting browser
240
filtered := []string{}
241
for _, result := range results {
242
if strings.Contains(result, "[launcher.Browser]") {
243
continue
244
}
245
filtered = append(filtered, result)
246
}
247
return filtered
248
}
249
250
// filterUnsignedTemplatesWarnings filters out warning messages about unsigned templates
251
func filterUnsignedTemplatesWarnings(results []string) []string {
252
filtered := []string{}
253
unsignedTemplatesRegex := regexp.MustCompile(`Loading \d+ unsigned templates for scan\. Use with caution\.`)
254
for _, result := range results {
255
if unsignedTemplatesRegex.MatchString(result) {
256
continue
257
}
258
filtered = append(filtered, result)
259
}
260
return filtered
261
}
262
263