From e97b0ae215eb63a609612aa75f83e0f2231dac60 Mon Sep 17 00:00:00 2001 From: DMarinhoCodacy Date: Thu, 12 Nov 2026 20:05:33 +0000 Subject: [PATCH 1/3] fix csharp.certificate.validation.rule --- Dockerfile | 5 ++++- all.json | 1 + probe.json | 1 + scripts/hotfix-rules.sh | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 all.json create mode 100644 probe.json create mode 100644 scripts/hotfix-rules.sh 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/all.json b/all.json new file mode 100644 index 0000000..7e059f4 --- /dev/null +++ b/all.json @@ -0,0 +1 @@ +{"version":"1.33.1","results":[],"errors":[],"paths":{"scanned":["/tmp/d/a.py"]},"interfile_languages_used":[],"skipped_rules":[]} diff --git a/probe.json b/probe.json new file mode 100644 index 0000000..ad44d18 --- /dev/null +++ b/probe.json @@ -0,0 +1 @@ +{"version":"1.33.1","results":[{"check_id":"docs.csharp_crypto_rule-CertificateValidationDisabled","path":"/tmp/p/Probe.cs","start":{"line":4,"col":5,"offset":56},"end":{"line":4,"col":109,"offset":160},"extra":{"metavars":{"$CALLBACK":{"start":{"line":4,"col":64,"offset":115},"end":{"line":4,"col":108,"offset":159},"abstract_content":"(sender certificate chain errors)=>true"}},"message":"The `ServicePointManager.ServerCertificateValidationCallback` event has been set\nto always return `true`, which effectively disables the validation of server\ncertificates.\n\nThis allows for an adversary who is in between the application and the target host to intercept\npotentially sensitive information or transmit malicious data.\n\nRemove the callback function that is returning true to allow normal certificate validation to\nproceed.\nWhen no callback is provided, the client will validate that the certificate name matches the\nhostname\nthat was used when creating the request.\n\nFor more information on the `ServerCertificateValidationCallback` property see:\nhttps://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback\n","metadata":{"shortDescription":"Certificate validation disabled","category":"security","owasp":["A3:2017-Sensitive Data Exposure","A07:2021-Identification and Authentication Failures","A07:2025-Authentication Failures"],"cwe":"CWE-295","security-severity":"Medium"},"severity":"WARNING","fingerprint":"44659c6bd517e8ff87f37d524fc081b9a50537bfc45f9c699bb1c1acf11f8e51a71e558cdffc41439ff78ced330dd5dbd37b24774e4f50a022531e9d49190e23_0","lines":" ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;","is_ignored":false,"validation_state":"NO_VALIDATOR","engine_kind":"OSS"}}],"errors":[],"paths":{"scanned":["/tmp/p/Probe.cs"]},"interfile_languages_used":[],"skipped_rules":[]} 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 From b6096af0484aefa756536db4baaf806158468d5e Mon Sep 17 00:00:00 2001 From: DMarinhoCodacy Date: Thu, 12 Nov 2026 20:19:53 +0000 Subject: [PATCH 2/3] fix exit code 2 --- internal/tool/command.go | 35 +++++++++++++++-- internal/tool/command_test.go | 71 ++++++++++++++++++++++++++++++++++- 2 files changed, 102 insertions(+), 4 deletions(-) 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 From 6fdf47dc417a8b37b720f2ec71af95345dabcdf2 Mon Sep 17 00:00:00 2001 From: DMarinhoCodacy Date: Thu, 12 Nov 2026 20:21:36 +0000 Subject: [PATCH 3/3] remove test files --- all.json | 1 - probe.json | 1 - 2 files changed, 2 deletions(-) delete mode 100644 all.json delete mode 100644 probe.json diff --git a/all.json b/all.json deleted file mode 100644 index 7e059f4..0000000 --- a/all.json +++ /dev/null @@ -1 +0,0 @@ -{"version":"1.33.1","results":[],"errors":[],"paths":{"scanned":["/tmp/d/a.py"]},"interfile_languages_used":[],"skipped_rules":[]} diff --git a/probe.json b/probe.json deleted file mode 100644 index ad44d18..0000000 --- a/probe.json +++ /dev/null @@ -1 +0,0 @@ -{"version":"1.33.1","results":[{"check_id":"docs.csharp_crypto_rule-CertificateValidationDisabled","path":"/tmp/p/Probe.cs","start":{"line":4,"col":5,"offset":56},"end":{"line":4,"col":109,"offset":160},"extra":{"metavars":{"$CALLBACK":{"start":{"line":4,"col":64,"offset":115},"end":{"line":4,"col":108,"offset":159},"abstract_content":"(sender certificate chain errors)=>true"}},"message":"The `ServicePointManager.ServerCertificateValidationCallback` event has been set\nto always return `true`, which effectively disables the validation of server\ncertificates.\n\nThis allows for an adversary who is in between the application and the target host to intercept\npotentially sensitive information or transmit malicious data.\n\nRemove the callback function that is returning true to allow normal certificate validation to\nproceed.\nWhen no callback is provided, the client will validate that the certificate name matches the\nhostname\nthat was used when creating the request.\n\nFor more information on the `ServerCertificateValidationCallback` property see:\nhttps://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback\n","metadata":{"shortDescription":"Certificate validation disabled","category":"security","owasp":["A3:2017-Sensitive Data Exposure","A07:2021-Identification and Authentication Failures","A07:2025-Authentication Failures"],"cwe":"CWE-295","security-severity":"Medium"},"severity":"WARNING","fingerprint":"44659c6bd517e8ff87f37d524fc081b9a50537bfc45f9c699bb1c1acf11f8e51a71e558cdffc41439ff78ced330dd5dbd37b24774e4f50a022531e9d49190e23_0","lines":" ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;","is_ignored":false,"validation_state":"NO_VALIDATOR","engine_kind":"OSS"}}],"errors":[],"paths":{"scanned":["/tmp/p/Probe.cs"]},"interfile_languages_used":[],"skipped_rules":[]}