Path: blob/dev/cmd/integration-test/integration-test.go
2070 views
package main12import (3"flag"4"fmt"5"os"6"regexp"7"runtime"8"strings"910"github.com/kitabisa/go-ci"11"github.com/logrusorgru/aurora"1213"github.com/projectdiscovery/gologger"14"github.com/projectdiscovery/nuclei/v3/pkg/testutils"15"github.com/projectdiscovery/nuclei/v3/pkg/testutils/fuzzplayground"16sliceutil "github.com/projectdiscovery/utils/slice"17)1819type TestCaseInfo struct {20Path string21TestCase testutils.TestCase22DisableOn func() bool23}2425var (26debug = os.Getenv("DEBUG") == "true"27customTests = os.Getenv("TESTS")28protocol = os.Getenv("PROTO")2930success = aurora.Green("[✓]").String()31failed = aurora.Red("[✘]").String()3233protocolTests = map[string][]TestCaseInfo{34"http": httpTestcases,35"interactsh": interactshTestCases,36"network": networkTestcases,37"dns": dnsTestCases,38"workflow": workflowTestcases,39"loader": loaderTestcases,40"profile-loader": profileLoaderTestcases,41"websocket": websocketTestCases,42"headless": headlessTestcases,43"whois": whoisTestCases,44"ssl": sslTestcases,45"library": libraryTestcases,46"templatesPath": templatesPathTestCases,47"templatesDir": templatesDirTestCases,48"file": fileTestcases,49"offlineHttp": offlineHttpTestcases,50"customConfigDir": customConfigDirTestCases,51"fuzzing": fuzzingTestCases,52"code": codeTestCases,53"multi": multiProtoTestcases,54"generic": genericTestcases,55"dsl": dslTestcases,56"flow": flowTestcases,57"javascript": jsTestcases,58"matcher-status": matcherStatusTestcases,59"exporters": exportersTestCases,60}61// flakyTests are run with a retry count of 362flakyTests = map[string]bool{63"protocols/http/self-contained-file-input.yaml": true,64}6566// For debug purposes67runProtocol = ""68runTemplate = ""69extraArgs = []string{}70interactshRetryCount = 371)7273func main() {74flag.StringVar(&runProtocol, "protocol", "", "run integration tests of given protocol")75flag.StringVar(&runTemplate, "template", "", "run integration test of given template")76flag.Parse()7778// allows passing extra args to nuclei79eargs := os.Getenv("DebugExtraArgs")80if eargs != "" {81extraArgs = strings.Split(eargs, " ")82testutils.ExtraDebugArgs = extraArgs83}8485if runProtocol != "" {86debugTests()87os.Exit(1)88}8990// start fuzz playground server91defer fuzzplayground.Cleanup()92server := fuzzplayground.GetPlaygroundServer()93defer func() {94_ = server.Close()95}()96go func() {97if err := server.Start("localhost:8082"); err != nil {98if !strings.Contains(err.Error(), "Server closed") {99gologger.Fatal().Msgf("Could not start server: %s\n", err)100}101}102}()103104customTestsList := normalizeSplit(customTests)105106failedTestTemplatePaths := runTests(customTestsList)107108if len(failedTestTemplatePaths) > 0 {109if ci.IsCI() {110// run failed tests again assuming they are flaky111// if they fail as well only then we assume that there is an actual issue112fmt.Println("::group::Running failed tests again")113failedTestTemplatePaths = runTests(failedTestTemplatePaths)114fmt.Println("::endgroup::")115116if len(failedTestTemplatePaths) > 0 {117debug = true118fmt.Println("::group::Failed integration tests in debug mode")119_ = runTests(failedTestTemplatePaths)120fmt.Println("::endgroup::")121} else {122fmt.Println("::group::All tests passed")123fmt.Println("::endgroup::")124os.Exit(0)125}126}127128os.Exit(1)129}130}131132// execute a testcase with retry and consider best of N133// intended for flaky tests like interactsh134func executeWithRetry(testCase testutils.TestCase, templatePath string, retryCount int) (string, error) {135var err error136for i := 0; i < retryCount; i++ {137err = testCase.Execute(templatePath)138if err == nil {139fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)140return "", nil141}142}143_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed after %v attempts : %s\n", failed, templatePath, retryCount, err)144return templatePath, err145}146147func debugTests() {148testCaseInfos := protocolTests[runProtocol]149for _, testCaseInfo := range testCaseInfos {150if (runTemplate != "" && !strings.Contains(testCaseInfo.Path, runTemplate)) ||151(testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn()) {152continue153}154if runProtocol == "interactsh" {155if _, err := executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount); err != nil {156fmt.Printf("\n%v", err.Error())157}158} else {159if _, err := execute(testCaseInfo.TestCase, testCaseInfo.Path); err != nil {160fmt.Printf("\n%v", err.Error())161}162}163}164}165166func runTests(customTemplatePaths []string) []string {167var failedTestTemplatePaths []string168169for proto, testCaseInfos := range protocolTests {170if protocol != "" {171if !strings.EqualFold(proto, protocol) {172continue173}174}175if len(customTemplatePaths) == 0 {176fmt.Printf("Running test cases for %q protocol\n", aurora.Blue(proto))177}178for _, testCaseInfo := range testCaseInfos {179if testCaseInfo.DisableOn != nil && testCaseInfo.DisableOn() {180fmt.Printf("skipping test case %v. disabled on %v.\n", aurora.Blue(testCaseInfo.Path), runtime.GOOS)181continue182}183if len(customTemplatePaths) == 0 || sliceutil.Contains(customTemplatePaths, testCaseInfo.Path) {184var failedTemplatePath string185var err error186if proto == "interactsh" || strings.Contains(testCaseInfo.Path, "interactsh") {187failedTemplatePath, err = executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount)188} else if flakyTests[testCaseInfo.Path] {189failedTemplatePath, err = executeWithRetry(testCaseInfo.TestCase, testCaseInfo.Path, interactshRetryCount)190} else {191failedTemplatePath, err = execute(testCaseInfo.TestCase, testCaseInfo.Path)192}193if err != nil {194failedTestTemplatePaths = append(failedTestTemplatePaths, failedTemplatePath)195}196}197}198}199200return failedTestTemplatePaths201}202203func execute(testCase testutils.TestCase, templatePath string) (string, error) {204if err := testCase.Execute(templatePath); err != nil {205_, _ = fmt.Fprintf(os.Stderr, "%s Test \"%s\" failed: %s\n", failed, templatePath, err)206return templatePath, err207}208209fmt.Printf("%s Test \"%s\" passed!\n", success, templatePath)210return "", nil211}212213func expectResultsCount(results []string, expectedNumbers ...int) error {214results = filterLines(results)215match := sliceutil.Contains(expectedNumbers, len(results))216if !match {217return 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:all218}219return nil220}221222func normalizeSplit(str string) []string {223return strings.FieldsFunc(str, func(r rune) bool {224return r == ','225})226}227228// filterLines applies all filtering functions to the results229func filterLines(results []string) []string {230results = filterHeadlessLogs(results)231results = filterUnsignedTemplatesWarnings(results)232return results233}234235// if chromium is not installed go-rod installs it in .cache directory236// this function filters out the logs from download and installation237func filterHeadlessLogs(results []string) []string {238// [launcher.Browser] 2021/09/23 15:24:05 [launcher] [info] Starting browser239filtered := []string{}240for _, result := range results {241if strings.Contains(result, "[launcher.Browser]") {242continue243}244filtered = append(filtered, result)245}246return filtered247}248249// filterUnsignedTemplatesWarnings filters out warning messages about unsigned templates250func filterUnsignedTemplatesWarnings(results []string) []string {251filtered := []string{}252unsignedTemplatesRegex := regexp.MustCompile(`Loading \d+ unsigned templates for scan\. Use with caution\.`)253for _, result := range results {254if unsignedTemplatesRegex.MatchString(result) {255continue256}257filtered = append(filtered, result)258}259return filtered260}261262263