nuclei/v2/cmd/integration-test/integration-test.go

189 lines
5.4 KiB
Go
Raw Normal View History

package main
import (
"flag"
"fmt"
"os"
"runtime"
"strings"
"github.com/logrusorgru/aurora"
2021-11-25 17:09:20 +02:00
"github.com/projectdiscovery/nuclei/v2/pkg/testutils"
2023-03-17 17:31:28 +01:00
sliceutil "github.com/projectdiscovery/utils/slice"
)
type TestCaseInfo struct {
Path string
TestCase testutils.TestCase
DisableOn func() bool
}
var (
debug = os.Getenv("DEBUG") == "true"
githubAction = os.Getenv("GH_ACTION") == "true"
customTests = os.Getenv("TESTS")
protocol = os.Getenv("PROTO")
success = aurora.Green("[✓]").String()
failed = aurora.Red("[✘]").String()
protocolTests = map[string][]TestCaseInfo{
2023-03-17 16:56:14 +01:00
"http": httpTestcases,
"interactsh": interactshTestCases,
2023-03-17 16:56:14 +01:00
"network": networkTestcases,
"dns": dnsTestCases,
"workflow": workflowTestcases,
"loader": loaderTestcases,
"websocket": websocketTestCases,
"headless": headlessTestcases,
"whois": whoisTestCases,
"ssl": sslTestcases,
Adding support for code templates (#2930) * Adding support for code templates * adding support for python, powershell and echo (test) * removing debug code * introducing command + trivial trust store mechanism * updating tests * adding basic tests * removing deprecated oracle * mod tidy * adding signature proto with debug prints * removing debug code * fixing test * fixing param order * improving test conditional build * disable file+offlinehttp+code with cloud * adding env vars * removing debug code * reorganizing test folders * adding code template test prototype with dummy priv/pub keys * bump go to 1.20 * fixing go version * fixing lint errors * adding fatal on pub-key test failure * switching to ecdsa asn1 * removing unused signature * fixing signature * adding more tests * extending core with engine args + powershell win test * adding unsigned code test * skip template signing in particular test case * improving test coverage * refactoring key names + adding already signed algo * removing debug code * fixing syntax * fixing lint issues * removing test template * fixing dns tests path * output fmt * adding interact * fixing lint issues * adding -sign cli helper * fixing nil pointer + parse inline keys * making rsa default * adding code prot. ref * moving file to correct loc * moving test * Issue 3339 headless fuzz (#3790) * Basic headless fuzzing * Remove debug statements * Add integration tests * Update template * Fix recognize payload value in matcher * Update tempalte * use req.SetURL() --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Auto Generate Syntax Docs + JSONSchema [Fri Jun 9 00:23:32 UTC 2023] :robot: * Add headless header and status matchers (#3794) * add headless header and status matchers * rename headers as header * add integration test for header+status * fix typo * add retry to py-interactsh integration test --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: Shubham Rasal <shubham@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: GitHub Action <action@github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
2023-06-09 17:24:24 +02:00
"library": libraryTestcases,
2023-03-17 16:56:14 +01:00
"templatesPath": templatesPathTestCases,
"templatesDir": templatesDirTestCases,
"file": fileTestcases,
"offlineHttp": offlineHttpTestcases,
"customConfigDir": customConfigDirTestCases,
"fuzzing": fuzzingTestCases,
Adding support for code templates (#2930) * Adding support for code templates * adding support for python, powershell and echo (test) * removing debug code * introducing command + trivial trust store mechanism * updating tests * adding basic tests * removing deprecated oracle * mod tidy * adding signature proto with debug prints * removing debug code * fixing test * fixing param order * improving test conditional build * disable file+offlinehttp+code with cloud * adding env vars * removing debug code * reorganizing test folders * adding code template test prototype with dummy priv/pub keys * bump go to 1.20 * fixing go version * fixing lint errors * adding fatal on pub-key test failure * switching to ecdsa asn1 * removing unused signature * fixing signature * adding more tests * extending core with engine args + powershell win test * adding unsigned code test * skip template signing in particular test case * improving test coverage * refactoring key names + adding already signed algo * removing debug code * fixing syntax * fixing lint issues * removing test template * fixing dns tests path * output fmt * adding interact * fixing lint issues * adding -sign cli helper * fixing nil pointer + parse inline keys * making rsa default * adding code prot. ref * moving file to correct loc * moving test * Issue 3339 headless fuzz (#3790) * Basic headless fuzzing * Remove debug statements * Add integration tests * Update template * Fix recognize payload value in matcher * Update tempalte * use req.SetURL() --------- Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> * Auto Generate Syntax Docs + JSONSchema [Fri Jun 9 00:23:32 UTC 2023] :robot: * Add headless header and status matchers (#3794) * add headless header and status matchers * rename headers as header * add integration test for header+status * fix typo * add retry to py-interactsh integration test --------- Co-authored-by: Sandeep Singh <sandeep@projectdiscovery.io> Co-authored-by: Shubham Rasal <shubham@projectdiscovery.io> Co-authored-by: Tarun Koyalwar <tarun@projectdiscovery.io> Co-authored-by: GitHub Action <action@github.com> Co-authored-by: Dogan Can Bakir <65292895+dogancanbakir@users.noreply.github.com> Co-authored-by: Tarun Koyalwar <45962551+tarunKoyalwar@users.noreply.github.com>
2023-06-09 17:24:24 +02:00
"code": codeTestCases,
"multi": multiProtoTestcases,
"generic": genericTestcases,
"dsl": dslTestcases,
"flow": flowTestcases,
javascript protocol for scripting (includes 15+ proto libs) (#4109) * rebase js-layer PR from @ice3man543 * package restructuring * working * fix duplicated event & matcher status * fix lint error * fix response field * add new functions * multiple minor improvements * fix incorrect stats in js protocol * sort output metadata in cli * remove temp files * remove dead code * add unit and integration test * fix lint error * add jsdoclint using llm * fix error in test * add js lint using llm * generate docs of libs * llm lint * remove duplicated docs * update generated docs * update prompt in doclint * update docs * temp disable version check test * fix unit test and add retry * fix panic in it * update and move jsdocs * updated jsdocs * update docs * update container platform in test * dir restructure and adding docs * add api_reference and remove markdown docs * fix imports * add javascript design and contribution docs * add js protocol documentation * update integration test and docs * update doc ext mdx->md * minor update to docs * new integration test and more * move go libs and add docs * gen new net docs and more * final docs update * add new devtool * use fastdialer * fix build fail * use fastdialer + network sandbox support * add reserved keyword 'Port' * update Port to new syntax * misc update * always enable templatectx in js protocol * move docs to 'js-proto-docs' repo * remove scrapefuncs binary --------- Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-09-16 16:02:17 +05:30
"javascript": jsTestcases,
2021-02-27 02:23:06 +05:30
}
// For debug purposes
runProtocol = ""
runTemplate = ""
extraArgs = []string{}
interactshRetryCount = 3
)
2021-02-27 02:23:06 +05:30
func main() {
flag.StringVar(&runProtocol, "protocol", "", "run integration tests of given protocol")
flag.StringVar(&runTemplate, "template", "", "run integration test of given template")
flag.Parse()
// allows passing extra args to nuclei
eargs := os.Getenv("DebugExtraArgs")
if eargs != "" {
extraArgs = strings.Split(eargs, " ")
testutils.ExtraDebugArgs = extraArgs
}
if runProtocol != "" {
debugTests()
os.Exit(1)
}
2023-03-17 17:31:28 +01:00
customTestsList := normalizeSplit(customTests)
failedTestTemplatePaths := runTests(customTestsList)
if len(failedTestTemplatePaths) > 0 {
if githubAction {
debug = true
fmt.Println("::group::Failed integration tests in debug mode")
_ = runTests(failedTestTemplatePaths)
fmt.Println("::endgroup::")
}
os.Exit(1)
}
}
// execute a testcase with retry and consider best of N
// intended for flaky tests like interactsh
func executeWithRetry(testCase testutils.TestCase, templatePath string, retryCount int) (string, error) {
var err error
for i := 0; i < retryCount; i++ {
err = testCase.Execute(templatePath)
if err == nil {
fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)
return "", nil
}
}
_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed after %v attempts : %s\n", failed, templatePath, retryCount, err)
return templatePath, err
}
func debugTests() {
testCaseInfos := protocolTests[runProtocol]
for _, testCaseInfo := range testCaseInfos {
if (runTemplate != "" && !strings.Contains(testCaseInfo.Path, runTemplate)) ||
(testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn()) {
continue
}
if runProtocol == "interactsh" {
if _, err := executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount); err != nil {
fmt.Printf("\n%v", err.Error())
}
} else {
if _, err := execute(testCaseInfo.TestCase, testCaseInfo.Path); err != nil {
fmt.Printf("\n%v", err.Error())
}
}
}
}
2023-03-17 17:31:28 +01:00
func runTests(customTemplatePaths []string) []string {
var failedTestTemplatePaths []string
for proto, testCaseInfos := range protocolTests {
if protocol != "" {
if !strings.EqualFold(proto, protocol) {
continue
}
}
if len(customTemplatePaths) == 0 {
fmt.Printf("Running test cases for %q protocol\n", aurora.Blue(proto))
}
for _, testCaseInfo := range testCaseInfos {
if testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn() {
fmt.Printf("skipping test case %v. disabled on %v.\n", aurora.Blue(testCaseInfo.Path), runtime.GOOS)
continue
}
if len(customTemplatePaths) == 0 || sliceutil.Contains(customTemplatePaths, testCaseInfo.Path) {
var failedTemplatePath string
var err error
2023-08-04 20:21:22 +05:30
if proto == "interactsh" || strings.Contains(testCaseInfo.Path, "interactsh") {
failedTemplatePath, err = executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount)
} else {
failedTemplatePath, err = execute(testCaseInfo.TestCase, testCaseInfo.Path)
}
if err != nil {
2023-03-17 17:31:28 +01:00
failedTestTemplatePaths = append(failedTestTemplatePaths, failedTemplatePath)
2021-02-27 02:23:06 +05:30
}
}
}
}
return failedTestTemplatePaths
}
func execute(testCase testutils.TestCase, templatePath string) (string, error) {
if err := testCase.Execute(templatePath); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed: %s\n", failed, templatePath, err)
return templatePath, err
}
fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)
return "", nil
}
func expectResultsCount(results []string, expectedNumbers ...int) error {
match := sliceutil.Contains(expectedNumbers, len(results))
if !match {
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
}
return nil
}
2023-03-17 17:31:28 +01:00
func normalizeSplit(str string) []string {
return strings.FieldsFunc(str, func(r rune) bool {
return r == ','
})
}