Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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" ]
35 changes: 32 additions & 3 deletions internal/tool/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
71 changes: 70 additions & 1 deletion internal/tool/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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")
}
}
41 changes: 41 additions & 0 deletions scripts/hotfix-rules.sh
Original file line number Diff line number Diff line change
@@ -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"