diff --git a/Dockerfile b/Dockerfile index abebacf..402bcee 100755 --- a/Dockerfile +++ b/Dockerfile @@ -12,6 +12,9 @@ RUN go build -o bin/codacy-opengrep -ldflags="-s -w" ./cmd/tool COPY .tool_version .tool_version COPY docs /docs RUN go run ./cmd/docgen -docFolder /docs +# TEMPORARY: fix rules that fail to parse in the current Opengrep version (see scripts/hotfix-rules.sh) +COPY scripts/hotfix-rules.sh /tmp/hotfix-rules.sh +RUN sh /tmp/hotfix-rules.sh /docs/rules.yaml # Compress binaries for smaller image size FROM alpine:3.21 AS compressor @@ -44,4 +47,4 @@ COPY --from=builder --chown=docker:docker /docs /docs COPY --from=compressor /src/bin /dist/bin USER docker -CMD [ "/dist/bin/codacy-opengrep" ] +CMD [ "/dist/bin/codacy-opengrep" ] \ No newline at end of file diff --git a/internal/tool/command.go b/internal/tool/command.go index 590db82..448d6d5 100644 --- a/internal/tool/command.go +++ b/internal/tool/command.go @@ -40,10 +40,23 @@ type SemgrepExtra struct { } type SemgrepError struct { - Message string `json:"message"` + Level string `json:"level"` + RuleID string `json:"rule_id"` + Message string `json:"message"` + // Opengrep reports the file of an error in the top-level "path" field + Path string `json:"path"` Location SemgrepErrorLocation `json:"location"` } +// file returns the file an error is about, or "" for errors that are not +// about a file, such as a rule that fails to parse. +func (e SemgrepError) file() string { + if e.Path != "" { + return e.Path + } + return e.Location.Path +} + type SemgrepErrorLocation struct { Path string `json:"path"` } @@ -132,6 +145,13 @@ func runCommand(cmd *exec.Cmd) (*string, *string, error) { var stderr bytes.Buffer cmd.Stderr = &stderr cmdOutput, err := cmd.Output() + // Opengrep exits 2 when an error-level problem occurred (e.g. a rule that fails + // to parse, which it then skips) but still prints the full JSON report. Its + // errors are handled by appendErrorToResult, so the results are kept + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 && json.Valid(cmdOutput) { + err = nil + } if err != nil { stderrString := stderr.String() return nil, &stderrString, err @@ -215,14 +235,23 @@ func appendErrorToResult(result []codacy.Result, semgrepOutput SemgrepOutput) [] // The error message already with sizeMessage length truncatedMessage := semgrepError.Message[:sizeMessage] + file := semgrepError.file() + if file == "" { + // Not about a user file (e.g. a rule that fails to parse, which Opengrep + // then skips): log it for us instead of reporting it as a file error + ruleID := strings.TrimPrefix(semgrepError.RuleID, "tmp.") + fmt.Fprintf(os.Stderr, "opengrep %s (rule %q): %s\n", semgrepError.Level, ruleID, truncatedMessage) + continue + } + // Append the error to the result but only if it doesn't contain // "Syntax error at line" to avoid logging syntax errors that are not relevant for the user if !strings.Contains(truncatedMessage, "Syntax error at line") { result = append(result, codacy.FileError{ Message: truncatedMessage, - File: semgrepError.Location.Path, + File: file, }) } } return result -} +} \ No newline at end of file diff --git a/internal/tool/command_test.go b/internal/tool/command_test.go index 914abd6..9b753fc 100644 --- a/internal/tool/command_test.go +++ b/internal/tool/command_test.go @@ -79,6 +79,44 @@ func TestRunCommand_Error(t *testing.T) { assert.Empty(t, stderr, "Expected empty stderr for a failed command") } +func TestRunCommand_ExitCode2WithReport(t *testing.T) { + // Arrange + report := `{"results": [], "errors": [{"level": "error", "message": "Out of memory"}]}` + mockCmd := exec.Command("sh", "-c", "echo '"+report+"'; echo 'Scan Status' >&2; exit 2") + + // Act + stdout, stderr, err := runCommand(mockCmd) + + // Assert + assert.NoError(t, err) + assert.Nil(t, stderr) + assert.Equal(t, report+"\n", *stdout) +} + +func TestRunCommand_ExitCode2WithoutReport(t *testing.T) { + // Arrange + mockCmd := exec.Command("sh", "-c", "echo 'not a report'; exit 2") + + // Act + stdout, _, err := runCommand(mockCmd) + + // Assert + assert.Error(t, err) + assert.Nil(t, stdout) +} + +func TestRunCommand_OtherExitCodeWithReport(t *testing.T) { + // Arrange + mockCmd := exec.Command("sh", "-c", `echo '{"results": [], "errors": []}'; exit 7`) + + // Act + stdout, _, err := runCommand(mockCmd) + + // Assert + assert.Error(t, err) + assert.Nil(t, stdout) +} + func TestParseCommandOutput(t *testing.T) { // Arrange mockPatternDescriptions := []codacy.PatternDescription{ @@ -258,6 +296,37 @@ func TestAppendErrorToResult(t *testing.T) { assert.Equal(t, mockSemgrepOutput.Errors[0].Location.Path, filePath) } +func TestAppendErrorToResult_TopLevelPath(t *testing.T) { + // Arrange + mockSemgrepOutput := SemgrepOutput{ + Errors: []SemgrepError{{Level: "warn", Message: "Partial parsing", Path: "src/a.yml"}}, + } + + // Act + result := appendErrorToResult([]codacy.Result{}, mockSemgrepOutput) + + // Assert + assert.Len(t, result, 1) + assert.Equal(t, "src/a.yml", result[0].GetFile()) +} + +func TestAppendErrorToResult_RuleErrorIsNotAFileError(t *testing.T) { + // Arrange + mockSemgrepOutput := SemgrepOutput{ + Errors: []SemgrepError{{ + Level: "error", + RuleID: "tmp.csharp_crypto_rule-CertificateValidationDisabled", + Message: "Rule parse error in rule tmp.csharp_crypto_rule-CertificateValidationDisabled", + }}, + } + + // Act + result := appendErrorToResult([]codacy.Result{}, mockSemgrepOutput) + + // Assert + assert.Empty(t, result, "Rule-level errors should be logged, not reported as file errors") +} + func TestWriteMessageWithEmptyMessageAndPatternDescriptionExists(t *testing.T) { // Arrange mockPatternDescriptions := []codacy.PatternDescription{ @@ -334,4 +403,4 @@ func TestWriteMessageWithInvalidPatternID(t *testing.T) { // Assert assert.Equal(t, docgen.GetFirstSentence(nonEmptyMessage), description, "Expected first sentence of non-empty message for invalid pattern ID") -} +} \ No newline at end of file diff --git a/scripts/hotfix-rules.sh b/scripts/hotfix-rules.sh new file mode 100644 index 0000000..fc496fd --- /dev/null +++ b/scripts/hotfix-rules.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# TEMPORARY: patch rules in the generated rules.yaml that fail to parse with +# the current Opengrep version. Remove each fix once it is fixed upstream. +# +# - csharp_crypto_rule-CertificateValidationDisabled (GitLab sast-rules): +# the pattern "(...) => true;" is not a valid C# expression pattern, so +# Opengrep reports a rule parse error and the scan exits with code 2. +# Dropping the trailing semicolon keeps the rule's behaviour. +# See https://github.com/codacy/codacy-opengrep/issues/44 +set -eu + +RULES="${1:-/docs/rules.yaml}" +TMP="$(mktemp)" + +awk -v target="csharp_crypto_rule-CertificateValidationDisabled" \ + -v broken="(...) => true;" ' + # Rules start at column 0 in the generated file; nested "- id:" lines + # inside patterns are indented and must not change the current rule. + /^- id:/ { + id = $0 + sub(/^- id:[ \t]*/, "", id) + gsub(/["\047 \t]/, "", id) + in_rule = (id == target) + } + in_rule && (i = index($0, broken)) > 0 { + # keep everything except the trailing ";" of the broken pattern + $0 = substr($0, 1, i + length(broken) - 2) substr($0, i + length(broken)) + patched++ + } + { print } + END { + if (patched == 0) { + print "hotfix-rules: no \"" broken "\" found in " target \ + " - fixed upstream? Remove this hotfix." > "/dev/stderr" + exit 1 + } + print "hotfix-rules: patched " patched " line(s) in " target > "/dev/stderr" + } +' "$RULES" > "$TMP" + +mv "$TMP" "$RULES" \ No newline at end of file