diff --git a/CHANGELOG.md b/CHANGELOG.md index 407d6e1..baae01a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Upgrade notes +- **`_enabled_rules` now takes effect.** An explicit allowlist + narrows the scan for that language. Clear the list at its source or set + `all_rules_enabled: 'true'` to run every rule. If every listed ID is unknown, + the scanner logs a warning and runs every rule for the language. - **Socket Tier 1 rejects four options in `socket_additional_params` that it used to ignore.** Socket npm CLI 1.19.0 makes `socket scan reach` fail on `--ignore-unresolved`, `--exclude-configs`, `--include-configs` and @@ -53,6 +57,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). instead of merging advisories of the same severity into one. Source installs now require `socketdev>=3.6.4`. +### Fixed +- SAST applies explicit rule allowlists and keeps finding fingerprints stable + when the installed rules directory is read-only. C and C++ have independent + allowlists. C# and .NET refer to the same analyzer and combine their lists. +- The Action and CLI default to empty rule allowlists. An empty list runs every + bundled rule for the enabled language. +- All-languages scans skip Erlang and Objective-C rule files because OpenGrep + cannot load them. +- Temporary custom and filtered SAST rule files are removed after each scan. + ## [3.5.0] - 2026-11-13 Minor rather than patch: Socket Tier 1 parses `socket_additional_params` diff --git a/action.yml b/action.yml index bd3b264..3ac7c26 100644 --- a/action.yml +++ b/action.yml @@ -177,9 +177,9 @@ inputs: required: false default: "" c_enabled_rules: - description: "Comma-separated list of C SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C SAST rules to run (default: empty, which runs every bundled C rule)" required: false - default: "c-buffer-overflow,c-format-string-vulnerability,c-command-injection,c-sql-injection,c-use-after-free,c-hardcoded-secrets,c-weak-crypto,c-ssl-issues" + default: "" c_sast_enabled: description: "Enable C SAST scanning" required: false @@ -197,9 +197,9 @@ inputs: required: false default: "" cpp_enabled_rules: - description: "Comma-separated list of C++ SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C++ SAST rules to run (default: empty, which runs every bundled C++ rule)" required: false - default: "c-buffer-overflow,c-format-string-vulnerability,c-command-injection,c-sql-injection,c-use-after-free,c-hardcoded-secrets,c-weak-crypto,c-ssl-issues,cpp-unsafe-cast,cpp-memory-management" + default: "" cpp_sast_enabled: description: "Enable C++ SAST scanning" required: false @@ -209,9 +209,9 @@ inputs: required: false default: "" csharp_enabled_rules: - description: "Comma-separated list of C# SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C# SAST rules to run (default: empty, which runs every bundled C# rule)" required: false - default: "dotnet-sql-injection,dotnet-command-injection,dotnet-code-injection,dotnet-unsafe-deserialization,dotnet-ldap-injection,dotnet-hardcoded-credentials,dotnet-ssl-bypass,dotnet-xxe-vulnerability,dotnet-xpath-injection" + default: "" csharp_sast_enabled: description: "Enable C# SAST scanning" required: false @@ -229,9 +229,9 @@ inputs: required: false default: "" dotnet_enabled_rules: - description: "Comma-separated list of .NET SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the .NET SAST rules to run (default: empty, which runs every bundled .NET rule)" required: false - default: "dotnet-sql-injection,dotnet-command-injection,dotnet-code-injection,dotnet-unsafe-deserialization,dotnet-ldap-injection,dotnet-hardcoded-credentials,dotnet-ssl-bypass,dotnet-xxe-vulnerability,dotnet-xpath-injection" + default: "" dotnet_sast_enabled: description: "Enable .NET SAST scanning" required: false @@ -241,9 +241,9 @@ inputs: required: false default: "" elixir_enabled_rules: - description: "Comma-separated list of Elixir SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Elixir SAST rules to run (default: empty, which runs every bundled Elixir rule)" required: false - default: "elixir-code-injection,elixir-sql-injection,elixir-command-injection,elixir-unsafe-deserialization,elixir-hardcoded-secrets,elixir-phoenix-ecto-injection" + default: "" elixir_sast_enabled: description: "Enable Elixir SAST scanning" required: false @@ -257,9 +257,9 @@ inputs: required: false default: "" go_enabled_rules: - description: "Comma-separated list of Go SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Go SAST rules to run (default: empty, which runs every bundled Go rule)" required: false - default: "go-hardcoded-credentials,go-bind-all-interfaces,go-unsafe-usage,go-ssh-insecure-ignore-host-key,go-profiling-endpoint-exposed,go-decompression-bomb,go-sql-format-string" + default: "" go_sast_enabled: description: "Enable Go SAST scanning" required: false @@ -273,9 +273,9 @@ inputs: required: false default: "" java_enabled_rules: - description: "Comma-separated list of Java SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Java SAST rules to run (default: empty, which runs every bundled Java rule)" required: false - default: "java-sql-injection,java-unsafe-deserialization,java-command-injection,java-ldap-injection,java-hardcoded-credentials,java-weak-crypto-md5,java-weak-crypto-sha1,java-xxe-vulnerability,java-ssl-bypass,java-weak-ssl-version,java-jndi-injection,java-el-injection" + default: "" java_sast_enabled: description: "Enable Java SAST scanning" required: false @@ -285,9 +285,9 @@ inputs: required: false default: "" javascript_enabled_rules: - description: "Comma-separated list of JavaScript/TypeScript SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the JavaScript/TypeScript SAST rules to run (default: empty, which runs every bundled JavaScript/TypeScript rule)" required: false - default: "js-eval-usage,js-sql-injection,js-command-injection,js-prototype-pollution,js-xss-innerhtml,js-path-traversal,js-tls-reject-unauthorized-false,js-weak-crypto-md5" + default: "" javascript_sast_enabled: description: "Enable JavaScript/TypeScript SAST scanning" required: false @@ -317,9 +317,9 @@ inputs: required: false default: "" kotlin_enabled_rules: - description: "Comma-separated list of Kotlin SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Kotlin SAST rules to run (default: empty, which runs every bundled Kotlin rule)" required: false - default: "kotlin-sql-injection,kotlin-command-injection,kotlin-code-injection,kotlin-unsafe-deserialization,kotlin-hardcoded-secrets,kotlin-ssl-bypass,kotlin-xxe-vulnerability,kotlin-ldap-injection" + default: "" kotlin_sast_enabled: description: "Enable Kotlin SAST scanning" required: false @@ -357,9 +357,9 @@ inputs: required: false default: "" php_enabled_rules: - description: "Comma-separated list of PHP SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the PHP SAST rules to run (default: empty, which runs every bundled PHP rule)" required: false - default: "php-code-injection,php-sql-injection,php-command-injection,php-unsafe-deserialization,php-ldap-injection,php-file-inclusion,php-xxe-vulnerability,php-hardcoded-secrets,php-path-traversal" + default: "" php_sast_enabled: description: "Enable PHP SAST scanning" required: false @@ -373,9 +373,9 @@ inputs: required: false default: "" python_enabled_rules: - description: "Comma-separated list of Python SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Python SAST rules to run (default: empty, which runs every bundled Python rule)" required: false - default: "python-exec-used,python-bad-file-permissions,python-hardcoded-password-string,python-eval-usage,python-request-without-cert-validation,python-ssl-bad-version,python-subprocess-shell-true,python-start-process-with-shell,python-sql-injection-format,python-flask-debug-true,python-jinja2-autoescape-false" + default: "" python_sast_enabled: description: "Enable Python SAST scanning" required: false @@ -385,9 +385,9 @@ inputs: required: false default: "" ruby_enabled_rules: - description: "Comma-separated list of Ruby SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Ruby SAST rules to run (default: empty, which runs every bundled Ruby rule)" required: false - default: "ruby-eval-injection,ruby-command-injection,ruby-sql-injection,ruby-unsafe-deserialization,ruby-hardcoded-secrets,ruby-ssl-verification-bypass,ruby-rails-find-by-sql-injection,ruby-rails-unsafe-constantize,ruby-xxe-vulnerability" + default: "" ruby_sast_enabled: description: "Enable Ruby SAST scanning" required: false @@ -397,9 +397,9 @@ inputs: required: false default: "" rust_enabled_rules: - description: "Comma-separated list of Rust SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Rust SAST rules to run (default: empty, which runs every bundled Rust rule)" required: false - default: "rust-command-injection,rust-unsafe-deserialization,rust-sql-injection,rust-hardcoded-secrets,rust-insecure-tls,rust-buffer-overflow-potential" + default: "" rust_sast_enabled: description: "Enable Rust SAST scanning" required: false @@ -409,9 +409,9 @@ inputs: required: false default: "" scala_enabled_rules: - description: "Comma-separated list of Scala SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Scala SAST rules to run (default: empty, which runs every bundled Scala rule)" required: false - default: "scala-sql-injection,scala-code-injection,scala-command-injection,scala-unsafe-deserialization,scala-hardcoded-secrets,scala-ssl-bypass,scala-slick-sql-injection" + default: "" scala_sast_enabled: description: "Enable Scala SAST scanning" required: false @@ -445,9 +445,9 @@ inputs: required: false default: "" swift_enabled_rules: - description: "Comma-separated list of Swift SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Swift SAST rules to run (default: empty, which runs every bundled Swift rule)" required: false - default: "swift-sql-injection,swift-command-injection,swift-unsafe-deserialization,swift-hardcoded-secrets,swift-ssl-bypass,swift-insecure-urlsession,swift-certificate-pinning-bypass" + default: "" swift_sast_enabled: description: "Enable Swift SAST scanning" required: false diff --git a/docs/github-action.md b/docs/github-action.md index 9dbad0a..3aaf5fa 100644 --- a/docs/github-action.md +++ b/docs/github-action.md @@ -512,7 +512,8 @@ Dockerfiles. The exceptions: - A blank `_enabled_rules` or `_disabled_rules` field is - skipped, so the workflow's value or the action's default list applies. + skipped, so the workflow's value applies. If the workflow sets none, every + bundled rule for the language runs. - A blank notification field (Slack, Jira, Microsoft Teams, generic webhook, Microsoft Sentinel, Sumo Logic) falls back to the workflow's value, and so does a blank GitHub token. A filled-in dashboard field still wins. @@ -557,17 +558,11 @@ directly as a step: ``` Only the flags you pass take precedence. Every other setting still comes from -the dashboard. Running the image directly differs from the action in two ways: - -- The action's default rule lists (`_enabled_rules` in - [`action.yml`](../action.yml)) don't apply. Where the dashboard's rule-list - fields are blank, SAST uses the image's own defaults from - [`connectors.yaml`](../socket_basics/connectors.yaml), which include more rules - for some languages. -- The step isn't tied to an action version, so update the image tag yourself - when you upgrade. To pin by digest, append `@sha256:` to the image. - `docker buildx imagetools inspect ghcr.io/socketdev/socket-basics:3.5.0` - prints the digest. +the dashboard. Running the image directly differs from the action in one way: +the step isn't tied to an action version, so update the image tag yourself +when you upgrade. To pin by digest, append `@sha256:` to the image. +`docker buildx imagetools inspect ghcr.io/socketdev/socket-basics:3.5.0` +prints the digest. See the [Parameters Reference](parameters.md) for every CLI flag. @@ -926,14 +921,11 @@ jobs: use_custom_sast_rules: 'true' custom_sast_rule_path: '.socket/rules' - # Optional: to avoid allowlist exclusions, run all rules for enabled languages. - all_rules_enabled: 'true' - # Optional: enable specific bundled or custom rule IDs. - javascript_enabled_rules: 'eval-usage,prototype-pollution' + javascript_enabled_rules: 'js-code-injection-eval,js-prototype-pollution' # Ignore one or more SAST rules globally or for exact repo-relative files - sast_ignore_overrides: 'js-sql-injection:index.js' + sast_ignore_overrides: 'js-code-injection-eval:index.js' ``` Important behavior: @@ -943,7 +935,9 @@ Important behavior: `use_custom_sast_rules`, `custom_sast_rule_path` and `sast_ignore_overrides` have no dashboard field and come from the workflow. See [Dashboard Settings and Workflow Inputs](#dashboard-settings-and-workflow-inputs). -- `_enabled_rules` is an allowlist and can suppress custom rule IDs. +- `_enabled_rules` limits the scan to the listed rule IDs, including + custom rule IDs. An empty list runs every rule. The step log warns about + unknown IDs. If every listed ID is unknown, every rule for the language runs. - `all_rules_enabled: 'true'` disables allowlist filtering for enabled languages. `sast_ignore_overrides` supports: @@ -1001,7 +995,7 @@ Every input has a CLI flag and environment-variable equivalent; the - `opengrep_notification_method` — Route SAST findings to one notifier (e.g. `console`, `slack`) **Rule Configuration (per language):** -- `_enabled_rules` — Comma-separated rules to enable +- `_enabled_rules` — Comma-separated rule IDs to run (default: empty, which runs every bundled rule) - `_disabled_rules` — Comma-separated rules to disable - `use_custom_sast_rules` — Enable custom SAST rule discovery from repo files - `custom_sast_rule_path` — Relative path to custom SAST rule directory diff --git a/docs/parameters.md b/docs/parameters.md index 3596a7c..72b3c08 100644 --- a/docs/parameters.md +++ b/docs/parameters.md @@ -82,7 +82,7 @@ GitHub Action input is delivered to the container as the environment variable | `--use-custom-sast-rules` | `use_custom_sast_rules` | `INPUT_USE_CUSTOM_SAST_RULES` | `use_custom_sast_rules` | Use custom SAST rules instead of bundled rules (falls back to bundled rules for languages without custom rules) | | `--custom-sast-rule-path` | `custom_sast_rule_path` | `INPUT_CUSTOM_SAST_RULE_PATH` | `custom_sast_rule_path` | Relative path to custom SAST rules directory (relative to workspace if set, otherwise cwd) | | `--sast-ignore-overrides` | `sast_ignore_overrides` | `INPUT_SAST_IGNORE_OVERRIDES` | `sast_ignore_overrides` | Comma-separated list of SAST ignore overrides in rule_id or rule_id:path format | -| `---enabled-rules` | `_enabled_rules` | `INPUT__ENABLED_RULES` | `_enabled_rules` | Comma-separated allowlist of rules for one language (defaults to the high-confidence set). | +| `---enabled-rules` | `_enabled_rules` | `INPUT__ENABLED_RULES` | `_enabled_rules` | Comma-separated allowlist of rule IDs for one language. Empty (the default) runs every bundled rule for the language. | | `---disabled-rules` | `_disabled_rules` | `INPUT__DISABLED_RULES` | `_disabled_rules` | Comma-separated rules to disable for one language. | `` is one of: `c`, `cpp`, `csharp`, `dotnet`, `elixir`, `go`, `java`, `javascript`, `kotlin`, `php`, `python`, `ruby`, `rust`, `scala`, `swift`. @@ -500,20 +500,25 @@ line carrying one does not pass it through. ### Language-Specific Rule Configuration -For each language, you can enable or disable specific rules: +By default every bundled rule for an enabled language runs. Use an enabled-rules +list to run only the listed rules. The log warns about IDs that match no rule. +If every ID is unknown, the scanner runs every rule for that language. Use the +`id` values in [`socket_basics/rules/`](../socket_basics/rules/) or in your custom +rule files. C and C++ have independent allowlists. C# and .NET use the same +analyzer and combine the lists for enabled aliases. **Pattern:** `---enabled-rules` or `---disabled-rules` **Examples:** ```bash # Enable specific Python rules -socket-basics --python --python-enabled-rules "sql-injection,xss-detection" +socket-basics --python --python-enabled-rules "python-sql-injection,python-command-injection" # Disable specific JavaScript rules -socket-basics --javascript --javascript-disabled-rules "console-log,debugger-statement" +socket-basics --javascript --javascript-disabled-rules "js-debugger-statement,js-parseint-missing-radix" # Enable specific Go rules -socket-basics --go --go-enabled-rules "error-handling,sql-injection" +socket-basics --go --go-enabled-rules "go-sql-format-string,go-hardcoded-credentials" ``` **Available for:** diff --git a/socket_basics/connectors.yaml b/socket_basics/connectors.yaml index 2ddcf6d..0261809 100644 --- a/socket_basics/connectors.yaml +++ b/socket_basics/connectors.yaml @@ -167,10 +167,10 @@ connectors: # Python rule configuration - name: python_enabled_rules option: --python-enabled-rules - description: "Comma-separated list of Python SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Python SAST rules to run (default: empty, which runs every bundled Python rule)" env_variable: INPUT_PYTHON_ENABLED_RULES type: str - default: "python-path-traversal-open,python-open-redirect,python-weak-hash-md5,python-weak-hash-sha1,python-weak-cipher-des,python-ssl-verify-disabled,python-insecure-tls-version,python-code-injection-eval,python-sql-injection,python-nosql-injection,python-command-injection,python-ldap-injection,python-xss-template,python-template-injection,python-yaml-load-unsafe,python-debug-mode-enabled,python-weak-session-config,python-insecure-file-permissions,python-jwt-no-verify,python-weak-jwt-algorithm,python-plain-text-password,python-unsafe-deserialization,python-ssrf-vulnerability,python-bare-except,python-dangerous-eval-exec,python-sql-format-string,python-insecure-temp-file" + default: "" - name: python_disabled_rules option: --python-disabled-rules description: "Comma-separated list of Python SAST rules to disable" @@ -181,10 +181,10 @@ connectors: # JavaScript/TypeScript rule configuration - name: javascript_enabled_rules option: --javascript-enabled-rules - description: "Comma-separated list of JavaScript/TypeScript SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the JavaScript/TypeScript SAST rules to run (default: empty, which runs every bundled JavaScript/TypeScript rule)" env_variable: INPUT_JAVASCRIPT_ENABLED_RULES type: str - default: "js-code-injection-eval,js-sql-injection,js-nosql-injection,js-command-injection,js-ldap-injection,js-prototype-pollution,js-xss-innerhtml,js-dom-xss,js-path-traversal,js-open-redirect,js-cors-allow-all,js-weak-hash-md5,js-weak-hash-sha1,js-hardcoded-secret,js-weak-cipher,js-tls-reject-unauthorized-false,js-insecure-tls-version,js-jwt-no-verify,js-weak-jwt-secret,js-weak-session-cookie,js-default-credentials,js-error-stack-exposed,js-unsafe-deserialization,js-ssrf-vulnerability,js-react-dangerous-html,js-unsafe-buffer,js-unsafe-file-operations,js-unsafe-process-spawn,js-debugger-statement,js-parseint-missing-radix" + default: "" - name: javascript_disabled_rules option: --javascript-disabled-rules description: "Comma-separated list of JavaScript/TypeScript SAST rules to disable" @@ -201,10 +201,10 @@ connectors: # Go rule configuration - name: go_enabled_rules option: --go-enabled-rules - description: "Comma-separated list of Go SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Go SAST rules to run (default: empty, which runs every bundled Go rule)" env_variable: INPUT_GO_ENABLED_RULES type: str - default: "go-hardcoded-credentials,go-ssh-insecure-ignore-host-key,go-sql-format-string,go-sql-string-concat,go-command-execution,go-file-path-traversal,go-zip-traversal,go-bad-tls-connection,go-import-des,go-import-rc4,go-empty-password,go-sql-direct-concat" + default: "" - name: go_disabled_rules option: --go-disabled-rules description: "Comma-separated list of Go SAST rules to disable" @@ -215,10 +215,10 @@ connectors: # Java rule configuration - name: java_enabled_rules option: --java-enabled-rules - description: "Comma-separated list of Java SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Java SAST rules to run (default: empty, which runs every bundled Java rule)" env_variable: INPUT_JAVA_ENABLED_RULES type: str - default: "java-reflection-injection,java-sql-injection,java-unsafe-deserialization,java-command-injection,java-ldap-injection,java-hardcoded-credentials,java-weak-crypto-md5,java-weak-crypto-sha1,java-insecure-random,java-xxe-vulnerability,java-path-traversal,java-ssl-bypass,java-spring-security-bypass,java-jpa-sql-injection,java-struts-ognl-injection,java-jndi-injection,java-el-injection,java-template-injection,java-file-upload-no-validation" + default: "" - name: java_disabled_rules option: --java-disabled-rules description: "Comma-separated list of Java SAST rules to disable" @@ -229,10 +229,10 @@ connectors: # PHP rule configuration - name: php_enabled_rules option: --php-enabled-rules - description: "Comma-separated list of PHP SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the PHP SAST rules to run (default: empty, which runs every bundled PHP rule)" env_variable: INPUT_PHP_ENABLED_RULES type: str - default: "php-code-injection,php-sql-injection,php-command-injection,php-unsafe-deserialization,php-ldap-injection,php-file-inclusion,php-xss,php-hardcoded-secrets,php-path-traversal,php-open-redirect,php-xxe-vulnerability,php-laravel-security,php-wordpress-security,php-codeigniter-security,php-file-upload-vulnerability,php-insecure-direct-object-reference,php-prepared-statement-injection" + default: "" - name: php_disabled_rules option: --php-disabled-rules description: "Comma-separated list of PHP SAST rules to disable" @@ -243,10 +243,10 @@ connectors: # Ruby rule configuration - name: ruby_enabled_rules option: --ruby-enabled-rules - description: "Comma-separated list of Ruby SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Ruby SAST rules to run (default: empty, which runs every bundled Ruby rule)" env_variable: INPUT_RUBY_ENABLED_RULES type: str - default: "ruby-eval-injection,ruby-command-injection,ruby-sql-injection,ruby-unsafe-deserialization,ruby-dynamic-method-definition,ruby-hardcoded-secrets,ruby-path-traversal,ruby-open-redirect,ruby-xss-raw-output,ruby-ssl-verification-bypass,ruby-weak-crypto,ruby-rails-find-by-sql-injection,ruby-rails-where-injection,ruby-template-injection" + default: "" - name: ruby_disabled_rules option: --ruby-disabled-rules description: "Comma-separated list of Ruby SAST rules to disable" @@ -257,10 +257,10 @@ connectors: # C# rule configuration - name: csharp_enabled_rules option: --csharp-enabled-rules - description: "Comma-separated list of C# SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C# SAST rules to run (default: empty, which runs every bundled C# rule)" env_variable: INPUT_CSHARP_ENABLED_RULES type: str - default: "dotnet-sql-injection,dotnet-command-injection,dotnet-code-injection,dotnet-unsafe-deserialization,dotnet-ldap-injection,dotnet-hardcoded-credentials,dotnet-weak-crypto-md5,dotnet-weak-crypto-sha1,dotnet-ssl-bypass,dotnet-xss-response-write,dotnet-path-traversal,dotnet-insecure-random,dotnet-xxe-vulnerability,dotnet-aspnet-validaterequest-false,dotnet-aspnet-viewstate-mac-disabled,dotnet-aspnetcore-auth-bypass,dotnet-ef-sql-injection,dotnet-broken-access-control,dotnet-crypto-failures,dotnet-xpath-injection,dotnet-auth-failures,dotnet-integrity-failures,dotnet-ssrf,dotnet-unsafe-code" + default: "" - name: csharp_disabled_rules option: --csharp-disabled-rules description: "Comma-separated list of C# SAST rules to disable" @@ -271,10 +271,10 @@ connectors: # .NET rule configuration - name: dotnet_enabled_rules option: --dotnet-enabled-rules - description: "Comma-separated list of .NET SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the .NET SAST rules to run (default: empty, which runs every bundled .NET rule)" env_variable: INPUT_DOTNET_ENABLED_RULES type: str - default: "dotnet-sql-injection,dotnet-command-injection,dotnet-code-injection,dotnet-unsafe-deserialization,dotnet-ldap-injection,dotnet-hardcoded-credentials,dotnet-weak-crypto-md5,dotnet-weak-crypto-sha1,dotnet-ssl-bypass,dotnet-xss-response-write,dotnet-path-traversal,dotnet-insecure-random,dotnet-xxe-vulnerability,dotnet-aspnet-validaterequest-false,dotnet-aspnet-viewstate-mac-disabled,dotnet-aspnetcore-auth-bypass,dotnet-ef-sql-injection,dotnet-broken-access-control,dotnet-crypto-failures,dotnet-xpath-injection,dotnet-auth-failures,dotnet-integrity-failures,dotnet-ssrf,dotnet-unsafe-code" + default: "" - name: dotnet_disabled_rules option: --dotnet-disabled-rules description: "Comma-separated list of .NET SAST rules to disable" @@ -285,10 +285,10 @@ connectors: # C rule configuration - name: c_enabled_rules option: --c-enabled-rules - description: "Comma-separated list of C SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C SAST rules to run (default: empty, which runs every bundled C rule)" env_variable: INPUT_C_ENABLED_RULES type: str - default: "c-buffer-overflow,c-format-string-vulnerability,c-command-injection,c-sql-injection,c-memory-management,c-use-after-free,c-integer-overflow,c-null-pointer-dereference,c-hardcoded-secrets,c-race-condition,cpp-unsafe-cast,cpp-memory-management,c-weak-crypto,c-ssl-issues,c-input-validation" + default: "" - name: c_disabled_rules option: --c-disabled-rules description: "Comma-separated list of C SAST rules to disable" @@ -299,10 +299,10 @@ connectors: # C++ rule configuration - name: cpp_enabled_rules option: --cpp-enabled-rules - description: "Comma-separated list of C++ SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the C++ SAST rules to run (default: empty, which runs every bundled C++ rule)" env_variable: INPUT_CPP_ENABLED_RULES type: str - default: "c-buffer-overflow,c-format-string-vulnerability,c-command-injection,c-sql-injection,c-memory-management,c-use-after-free,c-integer-overflow,c-null-pointer-dereference,c-hardcoded-secrets,c-race-condition,cpp-unsafe-cast,cpp-memory-management,c-weak-crypto,c-ssl-issues,c-input-validation" + default: "" - name: cpp_disabled_rules option: --cpp-disabled-rules description: "Comma-separated list of C++ SAST rules to disable" @@ -313,10 +313,10 @@ connectors: # Kotlin rule configuration - name: kotlin_enabled_rules option: --kotlin-enabled-rules - description: "Comma-separated list of Kotlin SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Kotlin SAST rules to run (default: empty, which runs every bundled Kotlin rule)" env_variable: INPUT_KOTLIN_ENABLED_RULES type: str - default: "kotlin-sql-injection,kotlin-command-injection,kotlin-code-injection,kotlin-unsafe-deserialization,kotlin-hardcoded-secrets,kotlin-weak-crypto-md5,kotlin-weak-crypto-sha1,kotlin-ssl-bypass,kotlin-path-traversal,kotlin-xss,kotlin-android-intent-user-input,kotlin-spring-security-bypass,kotlin-jpa-query-injection,kotlin-template-injection,kotlin-ldap-injection,kotlin-file-upload-no-validation,kotlin-xxe-vulnerability" + default: "" - name: kotlin_disabled_rules option: --kotlin-disabled-rules description: "Comma-separated list of Kotlin SAST rules to disable" @@ -327,10 +327,10 @@ connectors: # Scala rule configuration - name: scala_enabled_rules option: --scala-enabled-rules - description: "Comma-separated list of Scala SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Scala SAST rules to run (default: empty, which runs every bundled Scala rule)" env_variable: INPUT_SCALA_ENABLED_RULES type: str - default: "scala-sql-injection,scala-code-injection,scala-command-injection,scala-unsafe-deserialization,scala-hardcoded-secrets,scala-weak-crypto-md5,scala-weak-crypto-sha1,scala-ssl-bypass,scala-path-traversal,scala-xss-template,scala-slick-sql-injection,scala-json-injection,scala-file-upload-no-validation" + default: "" - name: scala_disabled_rules option: --scala-disabled-rules description: "Comma-separated list of Scala SAST rules to disable" @@ -341,10 +341,10 @@ connectors: # Swift rule configuration - name: swift_enabled_rules option: --swift-enabled-rules - description: "Comma-separated list of Swift SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Swift SAST rules to run (default: empty, which runs every bundled Swift rule)" env_variable: INPUT_SWIFT_ENABLED_RULES type: str - default: "swift-sql-injection,swift-command-injection,swift-unsafe-deserialization,swift-hardcoded-secrets,swift-weak-crypto-md5,swift-weak-crypto-sha1,swift-ssl-bypass,swift-path-traversal,swift-webview-xss,swift-ios-insecure-storage,swift-macos-privilege-escalation,swift-macos-code-signing,swift-certificate-pinning-bypass,swift-core-data-injection" + default: "" - name: swift_disabled_rules option: --swift-disabled-rules description: "Comma-separated list of Swift SAST rules to disable" @@ -355,10 +355,10 @@ connectors: # Rust rule configuration - name: rust_enabled_rules option: --rust-enabled-rules - description: "Comma-separated list of Rust SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Rust SAST rules to run (default: empty, which runs every bundled Rust rule)" env_variable: INPUT_RUST_ENABLED_RULES type: str - default: "rust-unsafe-usage,rust-command-injection,rust-unsafe-deserialization,rust-sql-injection,rust-hardcoded-secrets,rust-weak-crypto-md5,rust-weak-crypto-sha1,rust-insecure-tls,rust-path-traversal,rust-buffer-overflow-potential,rust-diesel-injection,rust-serde-security,rust-memory-safety" + default: "" - name: rust_disabled_rules option: --rust-disabled-rules description: "Comma-separated list of Rust SAST rules to disable" @@ -369,10 +369,10 @@ connectors: # Elixir rule configuration - name: elixir_enabled_rules option: --elixir-enabled-rules - description: "Comma-separated list of Elixir SAST rules to enable (default: high-confidence rules)" + description: "Comma-separated IDs of the Elixir SAST rules to run (default: empty, which runs every bundled Elixir rule)" env_variable: INPUT_ELIXIR_ENABLED_RULES type: str - default: "elixir-code-injection,elixir-sql-injection,elixir-command-injection,elixir-unsafe-deserialization,elixir-hardcoded-secrets,elixir-weak-crypto,elixir-path-traversal,elixir-xss,elixir-open-redirect,elixir-phoenix-xss,elixir-phoenix-ecto-injection,elixir-phoenix-file-upload" + default: "" - name: elixir_disabled_rules option: --elixir-disabled-rules description: "Comma-separated list of Elixir SAST rules to disable" diff --git a/socket_basics/core/config.py b/socket_basics/core/config.py index 6b8c0da..c88eca8 100644 --- a/socket_basics/core/config.py +++ b/socket_basics/core/config.py @@ -18,6 +18,10 @@ TRUE_STRINGS = ('true', '1', 'yes', 'on') FALSE_STRINGS = ('false', '0', 'no', 'off') +# Bundled rule files for languages OpenGrep cannot parse. Loading one makes +# OpenGrep report an UnknownLanguageError, so an all-languages scan skips them. +UNSUPPORTED_OPENGREP_RULE_FILES = frozenset({'erlang.yml', 'objective-c.yml'}) + def coerce_bool(value: Any, default: bool) -> bool: """Coerce a config value to a bool, tolerating the string forms. @@ -506,7 +510,7 @@ def should_run_sast(self) -> bool: for param in opengrep_config.get('parameters', []): param_name = param.get('name', '') - if 'sast_enabled' in param_name and self.get(param_name, False): + if 'sast_enabled' in param_name and coerce_bool(self.get(param_name), False): return True return False @@ -520,12 +524,12 @@ def should_run_sast(self) -> bool: 'php_sast_enabled', 'swift_sast_enabled', 'elixir_sast_enabled', 'erlang_sast_enabled', 'csharp_sast_enabled' ] - return any(self.get(lang, False) for lang in sast_langs) + return any(coerce_bool(self.get(lang), False) for lang in sast_langs) def build_opengrep_rules(self) -> List[str]: """Build list of rule files based on enabled languages""" # Explicit mapping from connector boolean flags to bundled rule filenames. - # Exclude languages for which we don't ship rule files (objective-c, erlang). + # Erlang and Objective-C are left out: see UNSUPPORTED_OPENGREP_RULE_FILES. language_rules = { 'python_sast_enabled': 'python.yml', 'go_sast_enabled': 'go.yml', @@ -550,23 +554,22 @@ def build_opengrep_rules(self) -> List[str]: # that are enabled. If no specific languages are enabled but --all-languages is # set, fall back to all bundled rule files. If neither is set, return empty # to allow upstream logic to skip scanning. - if self.get('all_rules_enabled', False): + if coerce_bool(self.get('all_rules_enabled'), False): rule_files = [] for flag, filename in language_rules.items(): - if self.get(flag, False): + if coerce_bool(self.get(flag), False): if filename not in rule_files: rule_files.append(filename) # If no specific language flags were enabled, but user set --all-languages, # return all bundled rules. if not rule_files: - if self.get('all_languages_enabled', False): + if coerce_bool(self.get('all_languages_enabled'), False): try: base_dir = Path(__file__).parent.parent rules_dir = base_dir / 'rules' found = [p.name for p in rules_dir.glob('*.yml') if p.is_file()] - excluded = {'objective-c.yml', 'erlang.yml'} - return [f for f in found if f not in excluded] + return [f for f in found if f not in UNSUPPORTED_OPENGREP_RULE_FILES] except Exception: return list({v for v in language_rules.values()}) # No languages enabled -> nothing to run @@ -576,7 +579,7 @@ def build_opengrep_rules(self) -> List[str]: rule_files = [] for flag, filename in language_rules.items(): - if self.get(flag, False): + if coerce_bool(self.get(flag), False): if filename not in rule_files: rule_files.append(filename) @@ -585,55 +588,42 @@ def build_opengrep_rules(self) -> List[str]: def get_enabled_rules_for_language(self, language: str) -> List[str]: """Get list of enabled rules for a specific language""" rules_param = f"{language}_enabled_rules" - rules_str = self.get(rules_param, "") - - if not rules_str or not rules_str.strip(): + rules_str = self.get(rules_param, "") or "" + if not isinstance(rules_str, str): + logger.warning("Expected a comma-separated string for %s. Running all rules for this language.", rules_param) return [] - return [rule.strip() for rule in rules_str.split(',') if rule.strip()] def build_filtered_opengrep_rules(self) -> Dict[str, List[str]]: - """Build mapping of rule files to specific rules that should be enabled""" - # Map connector flags to (rule filename, parameter name) so we can - # look up the user-specified enabled rules for that language. + """Build file-wide allowlists. C and C++ are filtered by analyzer.""" language_rule_mapping = { - 'python_sast_enabled': ('python.yml', 'python_enabled_rules'), - 'go_sast_enabled': ('go.yml', 'go_enabled_rules'), - 'golang_sast_enabled': ('go.yml', 'go_enabled_rules'), - 'javascript_sast_enabled': ('javascript_typescript.yml', 'javascript_enabled_rules'), - 'typescript_sast_enabled': ('javascript_typescript.yml', 'javascript_enabled_rules'), - 'java_sast_enabled': ('java.yml', 'java_enabled_rules'), - 'ruby_sast_enabled': ('ruby.yml', 'ruby_enabled_rules'), - 'csharp_sast_enabled': ('dotnet.yml', 'csharp_enabled_rules'), - 'dotnet_sast_enabled': ('dotnet.yml', 'dotnet_enabled_rules'), - 'scala_sast_enabled': ('scala.yml', 'scala_enabled_rules'), - 'kotlin_sast_enabled': ('kotlin.yml', 'kotlin_enabled_rules'), - 'rust_sast_enabled': ('rust.yml', 'rust_enabled_rules'), - 'c_sast_enabled': ('c_cpp.yml', 'c_enabled_rules'), - 'cpp_sast_enabled': ('c_cpp.yml', 'cpp_enabled_rules'), - 'php_sast_enabled': ('php.yml', 'php_enabled_rules'), - 'swift_sast_enabled': ('swift.yml', 'swift_enabled_rules'), - 'elixir_sast_enabled': ('elixir.yml', 'elixir_enabled_rules') + 'python_sast_enabled': ('python.yml', 'python'), + 'go_sast_enabled': ('go.yml', 'go'), + 'golang_sast_enabled': ('go.yml', 'go'), + 'javascript_sast_enabled': ('javascript_typescript.yml', 'javascript'), + 'typescript_sast_enabled': ('javascript_typescript.yml', 'javascript'), + 'java_sast_enabled': ('java.yml', 'java'), + 'ruby_sast_enabled': ('ruby.yml', 'ruby'), + 'csharp_sast_enabled': ('dotnet.yml', 'csharp'), + 'dotnet_sast_enabled': ('dotnet.yml', 'dotnet'), + 'scala_sast_enabled': ('scala.yml', 'scala'), + 'kotlin_sast_enabled': ('kotlin.yml', 'kotlin'), + 'rust_sast_enabled': ('rust.yml', 'rust'), + 'php_sast_enabled': ('php.yml', 'php'), + 'swift_sast_enabled': ('swift.yml', 'swift'), + 'elixir_sast_enabled': ('elixir.yml', 'elixir') } - rule_file_filters: Dict[str, set] = {} - - for flag, (rule_file, rules_param) in language_rule_mapping.items(): - if not self.get(flag, False): - continue - - # rules_param is the exact parameter name defined in connectors.yaml - enabled_rules = self.get(rules_param, "") - if not enabled_rules: + rule_file_filters: Dict[str, set[str]] = {} + for flag, (rule_file, language) in language_rule_mapping.items(): + if not coerce_bool(self.get(flag), False): continue - for r in [s.strip() for s in enabled_rules.split(',') if s.strip()]: - if rule_file not in rule_file_filters: - rule_file_filters[rule_file] = set() - rule_file_filters[rule_file].add(r) + enabled_rules = self.get_enabled_rules_for_language(language) + if enabled_rules: + rule_file_filters.setdefault(rule_file, set()).update(enabled_rules) - # Convert sets to lists for output - return {k: list(v) for k, v in rule_file_filters.items()} + return {k: sorted(v) for k, v in rule_file_filters.items()} def get_custom_rules_path(self) -> Optional[Path]: """Get the absolute path to custom SAST rules directory. diff --git a/socket_basics/core/connector/opengrep/__init__.py b/socket_basics/core/connector/opengrep/__init__.py index 80f8630..18a4606 100644 --- a/socket_basics/core/connector/opengrep/__init__.py +++ b/socket_basics/core/connector/opengrep/__init__.py @@ -2,21 +2,25 @@ """ OpenGrep SAST Scanner Connector -This connector composes a single OpenGrep command that includes full -language rule files and appends --exclude-rule flags for any rules that -should be skipped. It intentionally does not attempt per-rule fallbacks. +Run the enabled language rules in one OpenGrep invocation. Filtered scans +stage rule files with their original rule IDs to preserve finding fingerprints. """ import json import logging import os +import re +import shutil import subprocess import tempfile -import yaml +from contextlib import ExitStack from pathlib import Path from typing import Dict, Any, List +import yaml + from ..base import BaseConnector +from ...config import UNSUPPORTED_OPENGREP_RULE_FILES, coerce_bool # Opengrep produces canonical components/notifications directly # Import individual notifier modules @@ -41,6 +45,73 @@ def __init__(self, config): super().__init__(config) def scan(self) -> Dict[str, Any]: + with ExitStack() as cleanup: + return self._scan(cleanup) + + @staticmethod + def _matching_rule_ids(source: Path, enabled: set[str], available: set[str], language: str) -> set[str]: + if not enabled: + return available + unknown = enabled - available + if unknown: + logger.warning( + 'Unknown enabled-rule IDs for %s in %s: %s%s', + language, source, ', '.join(sorted(unknown)), + '. Running every rule for this language.' if unknown == enabled else '', + ) + return enabled & available or available + + def _filter_c_family_rules(self, source: Path, rules: list[dict], allowlists: dict[str, set[str]]) -> list[dict]: + # Restrict each rule's analyzers independently. OpenGrep handles shared + # headers as targets for either analyzer. + aliases = {'c++': 'cpp'} + selected = {} + for language, enabled in allowlists.items(): + available = { + rule['id'] for rule in rules + if isinstance(rule.get('id'), str) + and any(aliases.get(lang, lang) == language for lang in rule.get('languages', [])) + } + selected[language] = self._matching_rule_ids(source, enabled, available, language) + + kept = [] + for rule in rules: + languages = [ + language for language in rule.get('languages', []) + if rule.get('id') in selected.get(aliases.get(language, language), ()) + ] + if languages: + kept.append({**rule, 'languages': languages}) + return kept + + @staticmethod + def _stage_rule_configs(directory: Path, sources: dict[Path, dict | None]) -> list[Path]: + """Stage configs with the IDs OpenGrep would assign at their source paths.""" + configs = [] + cwd = Path.cwd() + for source, data in sources.items(): + if data is None: + data = yaml.safe_load(source.read_text(encoding='utf-8')) + # Match OpenGrep's local config namespace for --no-rewrite-rule-ids. + # Fingerprints include that namespace even when the config is staged elsewhere. + config_path = source.relative_to(cwd) if source.is_relative_to(cwd) else source + prefix = '.'.join(config_path.parts[:-1]).lstrip('./') + if prefix and isinstance(data, dict) and isinstance(data.get('rules'), list): + prefix = re.sub(r'[^a-zA-Z0-9._-]', '', prefix + '.') + rules = [ + {**rule, 'id': prefix + rule['id']} + if isinstance(rule, dict) and isinstance(rule.get('id'), str) else rule + for rule in data['rules'] + ] + data = {**data, 'rules': rules} + path = directory / f'{len(configs)}-{source.name}' + path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True), encoding='utf-8') + configs.append(path) + return configs + + def _scan(self, cleanup: ExitStack) -> Dict[str, Any]: + all_languages = coerce_bool(self.config.get('all_languages_enabled'), False) + all_rules = coerce_bool(self.config.get('all_rules_enabled'), False) # Determine enabled rule files try: rule_files = self.config.build_opengrep_rules() or [] @@ -48,13 +119,13 @@ def scan(self) -> Dict[str, Any]: rule_files = [] logger.info( "OpenGrep config summary: all_languages_enabled=%s all_rules_enabled=%s requested_rule_files=%s", - bool(self.config.get('all_languages_enabled', False)), - bool(self.config.get('all_rules_enabled', False)), + all_languages, + all_rules, rule_files, ) # If no languages selected and not explicitly allowing all, skip - if not rule_files and not self.config.get('all_languages_enabled', False): + if not rule_files and not all_languages: logger.debug('No SAST languages enabled; skipping OpenGrep') return {} @@ -75,12 +146,12 @@ def scan(self) -> Dict[str, Any]: logger.error('No rules directory found') return {} - if not rule_files and self.config.get('all_languages_enabled', False): + if not rule_files and all_languages: try: rule_files = [ p.name for p in Path(rules_dir).glob('*.yml') - if p.name != 'tests.yml' + if p.name != 'tests.yml' and p.name not in UNSUPPORTED_OPENGREP_RULE_FILES ] logger.info("Expanded all-languages scan to rule files: %s", rule_files) except Exception: @@ -101,120 +172,69 @@ def scan(self) -> Dict[str, Any]: logger.info(f"Custom SAST rules enabled, loading from: {custom_rules_path}") try: builder = CustomRulesBuilder(custom_rules_path) - custom_rule_files = builder.build_rule_files(rule_files) + try: + custom_rule_files = builder.build_rule_files(rule_files) + finally: + if builder.temp_dir is not None: + cleanup.callback(shutil.rmtree, builder.temp_dir, ignore_errors=True) except Exception as e: logger.error(f"Failed to build custom rule files: {e}", exc_info=True) custom_rule_files = {} - # Read filtered rule definitions if available - try: - filtered = self.config.build_filtered_opengrep_rules() or {} - except Exception: - filtered = {} - if filtered: - filtered_counts = {k: len(v or []) for k, v in filtered.items()} - logger.info("Per-language enabled-rule filters detected: %s", filtered_counts) - else: - logger.info("Per-language enabled-rule filters disabled for this run") - - # Debugging: log computed rule files and filtered rules for diagnosis - try: - logger.debug('Computed rule_files for OpenGrep: %s', rule_files) - logger.debug('Computed filtered rule mapping: %s', filtered) - except Exception: - pass - - if self.config.get('all_rules_enabled', False): - filtered = {} - - config_args: List[str] = [] - - # Build config_args using custom rules where available, falling back to bundled rules - # Process all enabled languages - use filtered rules if specified, otherwise use all rules + filters = {} + c_allowlists = {} + if not all_rules: + filters = self.config.build_filtered_opengrep_rules() + c_allowlists = { + language: set(self.config.get_enabled_rules_for_language(language)) + for language in ('c', 'cpp') + if coerce_bool(self.config.get(f'{language}_sast_enabled'), False) + } + + sources: dict[Path, dict | None] = {} for rf in rule_files: - # Check if we have a custom rule file for this language - using_custom_rules = bool(custom_rule_files and rf in custom_rule_files) - if custom_rule_files and rf in custom_rule_files: - p = custom_rule_files[rf] - logger.info("Using custom rules for %s from %s", rf, p) - else: - # Fall back to bundled rules - p = Path(rules_dir) / rf - if not p.exists(): - logger.debug('Rule file missing: %s', p) - continue - logger.info("Using bundled rules for %s from %s", rf, p) - - # Check if this language has specific rules enabled (filtered mode) - if filtered and rf in filtered: - enabled_ids = filtered[rf] - logger.info("Filtering rules for %s: %d enabled IDs configured", rf, len(enabled_ids)) - try: - with open(p, 'r') as fh: - data = yaml.safe_load(fh) or {} - all_ids = [r.get('id') for r in (data.get('rules') or []) if r.get('id')] - # Custom-rule mode can coexist with legacy bundled allowlists. - # If none of the configured enabled IDs match custom IDs, keep all - # custom IDs active to avoid silently disabling user-authored rules. - if using_custom_rules: - matched_enabled_ids = [rid for rid in all_ids if rid in (enabled_ids or [])] - if enabled_ids and not matched_enabled_ids: - logger.warning( - "No configured enabled-rule IDs matched custom rules for %s; using all custom rules from %s", - rf, - p, - ) - config_args.extend(['--config', str(p)]) - continue - to_exclude = [rid for rid in all_ids if rid not in matched_enabled_ids] - else: - to_exclude = [rid for rid in all_ids if rid not in (enabled_ids or [])] - config_args.extend(['--config', str(p)]) - for ex in to_exclude: - config_args.extend(['--exclude-rule', ex]) - except Exception: - logger.debug('Failed reading/parsing rule file %s', p, exc_info=True) - else: - # No specific rules configured - use all rules from this file - logger.debug(f"Using all rules for {rf}") - config_args.extend(['--config', str(p)]) - - # If nothing selected, only include all bundled rule files when the - # caller explicitly requested all languages or all rules. Otherwise - # skip scanning to avoid running unrelated language rules. - if not config_args: - # If all_rules_enabled is set, include all rule files for the - # languages that the config reports as enabled (build_opengrep_rules). - # Only when all_languages_enabled is True should we include every - # bundled rule file regardless of language flags. - if self.config.get('all_rules_enabled', False): - try: - rule_files = self.config.build_opengrep_rules() or [] - for rf in rule_files: - p = Path(rules_dir) / rf - if p.exists(): - config_args.extend(['--config', str(p)]) - except Exception: - logger.debug('Failed expanding all_rules into specific rule files', exc_info=True) - - if not config_args and self.config.get('all_languages_enabled', False): - try: - for p in Path(rules_dir).glob('*.yml'): - # Skip tests.yml from community rules - if p.name == 'tests.yml': - continue - config_args.extend(['--config', str(p)]) - except Exception: - pass - - if not config_args: - logger.debug('No rule files selected and not configured to include all; skipping OpenGrep') - return {} - - if not config_args: - logger.error('No valid rule files found') + source = custom_rule_files.get(rf, Path(rules_dir) / rf) + if not source.exists(): + logger.debug('Rule file missing: %s', source) + continue + sources[source] = None + filter_c_family = rf == 'c_cpp.yml' and any(c_allowlists.values()) + if rf not in filters and not filter_c_family: + continue + try: + data = yaml.safe_load(source.read_text(encoding='utf-8')) + rules = [rule for rule in data['rules'] if isinstance(rule, dict)] + if filter_c_family: + kept = self._filter_c_family_rules(source, rules, c_allowlists) + else: + available = {rule['id'] for rule in rules if isinstance(rule.get('id'), str)} + selected = self._matching_rule_ids(source, set(filters[rf]), available, rf) + kept = [rule for rule in rules if rule.get('id') in selected] + if kept != rules: + sources[source] = {**data, 'rules': kept} + except (OSError, TypeError, ValueError, KeyError, yaml.YAMLError): + logger.warning('Failed to filter %s. Running all rules from it.', source, exc_info=True) + + if not sources and all_languages: + sources = { + path: None for path in Path(rules_dir).glob('*.yml') + if path.name != 'tests.yml' and path.name not in UNSUPPORTED_OPENGREP_RULE_FILES + } + + if not sources: + logger.debug('No valid rule files selected. Skipping OpenGrep.') return {} + configs = list(sources) + preserve_rule_ids = False + if any(data is not None for data in sources.values()): + try: + directory = Path(cleanup.enter_context(tempfile.TemporaryDirectory(prefix='socket_filtered_rules_'))) + configs = self._stage_rule_configs(directory, sources) + preserve_rule_ids = True + except (OSError, ValueError, yaml.YAMLError): + logger.warning('Could not stage filtered rule configs. Running all selected rules.', exc_info=True) + # Run combined OpenGrep once with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tf: out_file = tf.name @@ -231,7 +251,11 @@ def scan(self) -> Dict[str, Any]: except Exception: pass - cmd.extend(config_args + targets) + if preserve_rule_ids: + cmd.append('--no-rewrite-rule-ids') + for path in configs: + cmd.extend(['--config', str(path)]) + cmd.extend(targets) logger.info('Running OpenGrep: %s', ' '.join(cmd)) try: diff --git a/socket_basics/core/connector/opengrep/custom_rules.py b/socket_basics/core/connector/opengrep/custom_rules.py index a13fe3f..402fd63 100644 --- a/socket_basics/core/connector/opengrep/custom_rules.py +++ b/socket_basics/core/connector/opengrep/custom_rules.py @@ -29,6 +29,7 @@ class CustomRulesBuilder: 'php': 'php.yml', 'c': 'c_cpp.yml', 'cpp': 'c_cpp.yml', + 'c++': 'c_cpp.yml', 'csharp': 'dotnet.yml', 'c#': 'dotnet.yml', 'kotlin': 'kotlin.yml', @@ -202,13 +203,3 @@ def _write_rule_files(self, rules_by_file: Dict[str, List[Dict[str, Any]]]) -> D continue return custom_rule_paths - - def cleanup(self) -> None: - """Clean up temporary rule files (optional, as temp files are typically auto-cleaned).""" - if self.temp_dir and self.temp_dir.exists(): - try: - import shutil - shutil.rmtree(self.temp_dir) - logger.debug(f"Cleaned up temporary rule directory: {self.temp_dir}") - except Exception as e: - logger.warning(f"Failed to clean up temporary rule directory {self.temp_dir}: {e}") diff --git a/tests/test_action_inputs_consistency.py b/tests/test_action_inputs_consistency.py index b587246..0da8cb8 100644 --- a/tests/test_action_inputs_consistency.py +++ b/tests/test_action_inputs_consistency.py @@ -67,3 +67,47 @@ def test_input_names_used_in_the_docs_are_declared() -> None: "scan_files", } assert documented <= inputs, f"undeclared: {sorted(documented - inputs)}" + + +def _bundled_rule_ids() -> set[str]: + ids: set[str] = set() + for path in (ROOT / "socket_basics" / "rules").glob("*.yml"): + for rule in (yaml.safe_load(path.read_text()) or {}).get("rules") or []: + ids.add(rule["id"]) + return ids + + +def test_default_rule_lists_name_only_existing_rules() -> None: + """A renamed rule must not leave a dead ID in a default allowlist.""" + known = _bundled_rule_ids() + defaults = { + f"action.yml:{name}": spec.get("default") or "" + for name, spec in _action()["inputs"].items() + if name.endswith(("_enabled_rules", "_disabled_rules")) + } + connectors = yaml.safe_load((ROOT / "socket_basics" / "connectors.yaml").read_text()) + for cfg in connectors["connectors"].values(): + for param in cfg.get("parameters") or []: + if param["name"].endswith(("_enabled_rules", "_disabled_rules")): + defaults[f"connectors.yaml:{param['name']}"] = param.get("default") or "" + unknown = { + where: sorted({i.strip() for i in value.split(",") if i.strip()} - known) + for where, value in defaults.items() + } + assert {k: v for k, v in unknown.items() if v} == {} + + +def test_sast_allowlists_default_to_empty_in_action_and_cli() -> None: + inputs = _action()["inputs"] + cli_params = { + param["name"]: param + for param in yaml.safe_load((ROOT / "socket_basics" / "connectors.yaml").read_text())[ + "connectors" + ]["opengrep"]["parameters"] + if param["name"].endswith("_enabled_rules") + } + assert cli_params + assert {name for name in inputs if name.endswith("_enabled_rules")} == set(cli_params) + for name, param in cli_params.items(): + assert inputs[name]["default"] == "", name + assert param["default"] == "", name diff --git a/tests/test_opengrep_custom_rules.py b/tests/test_opengrep_custom_rules.py index 3a85fad..b86a895 100644 --- a/tests/test_opengrep_custom_rules.py +++ b/tests/test_opengrep_custom_rules.py @@ -1,7 +1,11 @@ import json +import tempfile from pathlib import Path from types import SimpleNamespace +import pytest +import yaml + from socket_basics.core.config import Config from socket_basics.core.connector.opengrep import OpenGrepScanner @@ -28,9 +32,18 @@ def _write_custom_rules_file(path: Path, rule_ids: list[str]) -> None: path.write_text("\n".join(lines), encoding="utf-8") -def _mock_subprocess_run(monkeypatch, captured_cmd: list[str]): +def _mock_subprocess_run(monkeypatch, captured_cmd: list[str], configs: dict | None = None): + """Record the command. When ``configs`` is given, also record the rule IDs + in each ``--config`` file, keyed by path, while the files still exist.""" + def _runner(cmd, capture_output, text): captured_cmd.extend(cmd) + if configs is not None: + for i, arg in enumerate(cmd): + if arg == "--config": + path = Path(cmd[i + 1]) + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + configs[str(path)] = [r["id"] for r in data.get("rules") or []] out_file = cmd[cmd.index("--output") + 1] Path(out_file).write_text(json.dumps({"results": []}), encoding="utf-8") return SimpleNamespace(stdout="", stderr="", returncode=0) @@ -176,13 +189,15 @@ def test_custom_rules_ignore_nonmatching_bundled_allowlist_ids(tmp_path, monkeyp scanner.generate_notifications = lambda _: {} captured_cmd: list[str] = [] - _mock_subprocess_run(monkeypatch, captured_cmd) + configs: dict = {} + _mock_subprocess_run(monkeypatch, captured_cmd, configs) scanner.scan() - cmd_str = " ".join(captured_cmd) - assert "socket_custom_rules_" in cmd_str - assert "--exclude-rule org.no-eval" not in cmd_str - assert "--exclude-rule org.no-innerhtml" not in cmd_str + # No allowlist ID names a custom rule, so every custom rule runs. + assert "--exclude-rule" not in captured_cmd + [(path, ids)] = configs.items() + assert "socket_custom_rules_" in path + assert sorted(ids) == ["org.no-eval", "org.no-innerhtml"] def test_custom_rules_apply_allowlist_when_custom_ids_match(tmp_path, monkeypatch): @@ -214,9 +229,277 @@ def test_custom_rules_apply_allowlist_when_custom_ids_match(tmp_path, monkeypatc scanner.generate_notifications = lambda _: {} captured_cmd: list[str] = [] - _mock_subprocess_run(monkeypatch, captured_cmd) + configs: dict = {} + _mock_subprocess_run(monkeypatch, captured_cmd, configs) scanner.scan() - cmd_str = " ".join(captured_cmd) - assert "--exclude-rule org.no-innerhtml" in cmd_str - assert "--exclude-rule org.no-eval" not in cmd_str + assert "--exclude-rule" not in captured_cmd + [(path, ids)] = configs.items() + assert "--no-rewrite-rule-ids" in captured_cmd + assert "socket_filtered_rules_" in path + [rule_id] = ids + assert ".socket_custom_rules_" in rule_id + assert rule_id.endswith(".org.no-eval") + + +def _bundled_js_scanner(tmp_path, rule_ids: list[str], enabled: str) -> tuple[OpenGrepScanner, Path]: + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True, exist_ok=True) + bundled_rules_dir = tmp_path / "bundled-rules" + bundled_file = bundled_rules_dir / "javascript_typescript.yml" + _write_rule_file(bundled_file, rule_ids) + config = Config( + { + "workspace": str(workspace), + "output_dir": str(workspace), + "javascript_sast_enabled": True, + "javascript_enabled_rules": enabled, + "opengrep_rules_dir": str(bundled_rules_dir), + "all_languages_enabled": False, + "all_rules_enabled": False, + "verbose": False, + } + ) + scanner = OpenGrepScanner(config) + scanner._convert_to_socket_facts = lambda _: {"components": []} + scanner.generate_notifications = lambda _: {} + return scanner, bundled_file + + +def test_bundled_allowlist_passes_only_enabled_rules(tmp_path, monkeypatch): + scanner, bundled_file = _bundled_js_scanner(tmp_path, ["js-a", "js-b", "js-c"], "js-a,js-c") + + captured_cmd: list[str] = [] + configs: dict = {} + _mock_subprocess_run(monkeypatch, captured_cmd, configs) + scanner.scan() + + assert "--exclude-rule" not in captured_cmd + assert str(bundled_file) not in captured_cmd + [(path, ids)] = configs.items() + assert "--no-rewrite-rule-ids" in captured_cmd + assert [rule_id.rsplit(".", 1)[-1] for rule_id in ids] == ["js-a", "js-c"] + assert all(".bundled-rules." in rule_id for rule_id in ids) + assert Path(path).parent != bundled_file.parent + assert not Path(path).exists() + assert [p.name for p in bundled_file.parent.iterdir()] == [bundled_file.name] + + +def test_bundled_allowlist_warns_about_unknown_ids(tmp_path, monkeypatch, caplog): + scanner, _ = _bundled_js_scanner(tmp_path, ["js-a", "js-b"], "js-a,js-renamed-long-ago") + + configs: dict = {} + _mock_subprocess_run(monkeypatch, [], configs) + with caplog.at_level("WARNING"): + scanner.scan() + + [[rule_id]] = configs.values() + assert rule_id.endswith(".js-a") + assert "js-renamed-long-ago" in caplog.text + + +def test_bundled_allowlist_matching_nothing_runs_every_rule(tmp_path, monkeypatch, caplog): + scanner, bundled_file = _bundled_js_scanner(tmp_path, ["js-a", "js-b"], "js-typo") + + captured_cmd: list[str] = [] + configs: dict = {} + _mock_subprocess_run(monkeypatch, captured_cmd, configs) + with caplog.at_level("WARNING"): + scanner.scan() + + assert list(configs) == [str(bundled_file)] + assert "js-typo" in caplog.text + + +def test_all_rules_enabled_ignores_allowlist(tmp_path, monkeypatch): + scanner, bundled_file = _bundled_js_scanner(tmp_path, ["js-a", "js-b"], "js-a") + scanner.config.set("all_rules_enabled", True) + + configs: dict = {} + _mock_subprocess_run(monkeypatch, [], configs) + scanner.scan() + + assert configs == {str(bundled_file): ["js-a", "js-b"]} + + +def test_custom_rule_files_are_removed_after_the_scan(tmp_path, monkeypatch): + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True, exist_ok=True) + _write_custom_rules_file(workspace / ".socket" / "rules" / "org-rules.yml", ["org.no-eval"]) + bundled_rules_dir = tmp_path / "bundled-rules" + _write_rule_file(bundled_rules_dir / "javascript_typescript.yml", ["js-default-rule"]) + + config = Config( + { + "workspace": str(workspace), + "output_dir": str(workspace), + "javascript_sast_enabled": True, + "use_custom_sast_rules": True, + "custom_sast_rule_path": ".socket/rules", + "opengrep_rules_dir": str(bundled_rules_dir), + "all_languages_enabled": False, + "all_rules_enabled": False, + "verbose": False, + } + ) + scanner = OpenGrepScanner(config) + scanner._convert_to_socket_facts = lambda _: {"components": []} + scanner.generate_notifications = lambda _: {} + + configs: dict = {} + _mock_subprocess_run(monkeypatch, [], configs) + scanner.scan() + + [path] = configs + assert "socket_custom_rules_" in path + assert not Path(path).parent.exists() + + +def test_all_languages_scan_skips_rule_files_opengrep_cannot_load(tmp_path, monkeypatch): + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True, exist_ok=True) + bundled_rules_dir = tmp_path / "bundled-rules" + for name in ("python.yml", "erlang.yml", "objective-c.yml"): + _write_rule_file(bundled_rules_dir / name, [f"{name}-rule"]) + + config = Config( + { + "workspace": str(workspace), + "output_dir": str(workspace), + "opengrep_rules_dir": str(bundled_rules_dir), + "all_languages_enabled": True, + "all_rules_enabled": False, + "verbose": False, + } + ) + scanner = OpenGrepScanner(config) + scanner._convert_to_socket_facts = lambda _: {"components": []} + scanner.generate_notifications = lambda _: {} + + configs: dict = {} + _mock_subprocess_run(monkeypatch, [], configs) + scanner.scan() + + assert [Path(p).name for p in configs] == ["python.yml"] + + +def test_all_rules_and_languages_skip_rule_files_opengrep_cannot_load(): + rule_files = Config({"all_rules_enabled": True, "all_languages_enabled": True}).build_opengrep_rules() + assert "python.yml" in rule_files + assert not {"erlang.yml", "objective-c.yml"} & set(rule_files) + + +def _record_temp_paths(monkeypatch) -> list[Path]: + """Record temporary rule directories created during the scan.""" + created: list[Path] = [] + real_mkdtemp = tempfile.mkdtemp + + def _mkdtemp(*args, **kwargs): + path = real_mkdtemp(*args, **kwargs) + created.append(Path(path)) + return path + + monkeypatch.setattr(tempfile, "mkdtemp", _mkdtemp) + return created + + +def _custom_and_filtered_scanner(tmp_path) -> tuple[OpenGrepScanner, Path]: + """Scan custom JavaScript and bundled Python rules with allowlists.""" + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True, exist_ok=True) + _write_custom_rules_file(workspace / ".socket" / "rules" / "org-rules.yml", ["org.no-eval", "org.no-innerhtml"]) + bundled_rules_dir = tmp_path / "bundled-rules" + _write_rule_file(bundled_rules_dir / "javascript_typescript.yml", ["js-default-rule"]) + _write_rule_file(bundled_rules_dir / "python.yml", ["py-a", "py-b"]) + config = Config( + { + "workspace": str(workspace), + "output_dir": str(workspace), + "javascript_sast_enabled": True, + "javascript_enabled_rules": "org.no-eval", + "python_sast_enabled": True, + "python_enabled_rules": "py-a", + "use_custom_sast_rules": True, + "custom_sast_rule_path": ".socket/rules", + "opengrep_rules_dir": str(bundled_rules_dir), + "all_languages_enabled": False, + "all_rules_enabled": False, + "verbose": False, + } + ) + scanner = OpenGrepScanner(config) + scanner._convert_to_socket_facts = lambda _: {"components": []} + scanner.generate_notifications = lambda _: {} + return scanner, bundled_rules_dir + + +def _assert_all_removed(created: list[Path], bundled_rules_dir: Path) -> None: + assert created + assert not any(p.exists() for p in created) + assert sorted(p.name for p in bundled_rules_dir.iterdir()) == ["javascript_typescript.yml", "python.yml"] + + +def test_temp_rule_paths_are_removed_when_opengrep_is_missing(tmp_path, monkeypatch): + created = _record_temp_paths(monkeypatch) + scanner, bundled_rules_dir = _custom_and_filtered_scanner(tmp_path) + + def _missing(cmd, capture_output, text): + raise FileNotFoundError("opengrep") + + monkeypatch.setattr("socket_basics.core.connector.opengrep.subprocess.run", _missing) + assert scanner.scan() == {} + + assert sum(p.name.startswith("socket_custom_rules_") for p in created) == 1 + assert sum(p.name.startswith("socket_filtered_rules_") for p in created) == 1 + _assert_all_removed(created, bundled_rules_dir) + + +def test_temp_rule_paths_are_removed_when_the_scan_raises(tmp_path, monkeypatch): + created = _record_temp_paths(monkeypatch) + scanner, bundled_rules_dir = _custom_and_filtered_scanner(tmp_path) + + def _crash(cmd, capture_output, text): + raise RuntimeError("opengrep crashed") + + monkeypatch.setattr("socket_basics.core.connector.opengrep.subprocess.run", _crash) + with pytest.raises(RuntimeError, match="opengrep crashed"): + scanner.scan() + + _assert_all_removed(created, bundled_rules_dir) + + +def test_custom_rule_dir_is_removed_when_building_custom_rules_fails(tmp_path, monkeypatch): + created = _record_temp_paths(monkeypatch) + scanner, bundled_rules_dir = _custom_and_filtered_scanner(tmp_path) + + def _fail(self, rules_by_file): + raise OSError("disk full") + + monkeypatch.setattr( + "socket_basics.core.connector.opengrep.custom_rules.CustomRulesBuilder._write_rule_files", _fail + ) + _mock_subprocess_run(monkeypatch, []) + scanner.scan() + + assert any(p.name.startswith("socket_custom_rules_") for p in created) + _assert_all_removed(created, bundled_rules_dir) + + +@pytest.mark.parametrize( + "dotnet_enabled, dotnet_rules, expected", + [ + (True, "", ["rule-x"]), + (True, "rule-y,rule-x", ["rule-x", "rule-y"]), + ("false", "rule-y", ["rule-x"]), + ], +) +def test_csharp_and_dotnet_share_one_allowlist(dotnet_enabled, dotnet_rules, expected): + config = Config( + { + "csharp_sast_enabled": True, + "dotnet_sast_enabled": dotnet_enabled, + "csharp_enabled_rules": "rule-x", + "dotnet_enabled_rules": dotnet_rules, + } + ) + assert config.build_filtered_opengrep_rules() == {"dotnet.yml": expected} diff --git a/tests/test_opengrep_rule_filter_e2e.py b/tests/test_opengrep_rule_filter_e2e.py new file mode 100644 index 0000000..700296b --- /dev/null +++ b/tests/test_opengrep_rule_filter_e2e.py @@ -0,0 +1,174 @@ +"""End-to-end check that ``_enabled_rules`` narrows a real OpenGrep run. + +Asserting on the command line is not enough here: how OpenGrep matches and +reports rule IDs depends on how it loads the rule files, so a command that looks +right can still run every rule. These tests run the real binary on the bundled +JavaScript rules and check which rules report findings and their fingerprints. + +Skipped when ``opengrep`` is not on PATH, unless CI requires it. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +from socket_basics.core.config import Config +from socket_basics.core.connector.opengrep import OpenGrepScanner + +REQUIRE_OPENGREP_ENV = "SOCKET_BASICS_REQUIRE_OPENGREP" + +_HAVE_OPENGREP = shutil.which("opengrep") is not None +if not _HAVE_OPENGREP and os.environ.get(REQUIRE_OPENGREP_ENV): + pytest.fail( + f"{REQUIRE_OPENGREP_ENV} is set but opengrep is not on PATH", pytrace=False + ) + +pytestmark = pytest.mark.skipif( + not _HAVE_OPENGREP, + reason="opengrep is not installed; rule filter end-to-end tests skipped", +) + +# Reports js-code-injection-eval, js-weak-hash-md5, js-debugger-statement and +# others with the bundled javascript_typescript.yml rules. +APP_JS = """\ +const crypto = require("crypto"); +function handle(req) { + eval(req.query.code); + return crypto.createHash("md5").update(req.body).digest("hex"); +} +debugger; +""" + +_real_run = subprocess.run + + +def _run_scan(tmp_path: Path, monkeypatch, files: dict[str, str], **overrides) -> set[tuple[str, str, str]]: + workspace = tmp_path / "workspace" + workspace.mkdir(exist_ok=True) + for name, content in files.items(): + (workspace / name).write_text(content, encoding="utf-8") + + reported: set[tuple[str, str, str]] = set() + + def _run_and_record(cmd, **kwargs): + result = _real_run(cmd, **kwargs) + out_file = Path(cmd[cmd.index("--output") + 1]) + for r in json.loads(out_file.read_text() or "{}").get("results", []): + reported.add((Path(r["path"]).name, r["check_id"].rsplit(".", 1)[-1], r["extra"]["fingerprint"])) + return result + + monkeypatch.setattr( + "socket_basics.core.connector.opengrep.subprocess.run", _run_and_record + ) + + config = Config( + { + "workspace": str(workspace), + "output_dir": str(workspace), + "javascript_sast_enabled": True, + "all_languages_enabled": False, + "all_rules_enabled": False, + "verbose": False, + **overrides, + } + ) + scanner = OpenGrepScanner(config) + scanner._convert_to_socket_facts = lambda _: {"components": []} + scanner.generate_notifications = lambda _: {} + scanner.scan() + return reported + + +def _scan_findings(tmp_path: Path, monkeypatch, **overrides) -> set[tuple[str, str]]: + return { + (rule, fingerprint) + for _, rule, fingerprint in _run_scan(tmp_path, monkeypatch, {"app.js": APP_JS}, **overrides) + } + + +def _scan(tmp_path: Path, monkeypatch, **overrides) -> set[str]: + """Run the OpenGrep connector over APP_JS and return the reported rule IDs.""" + return {rule for rule, _ in _scan_findings(tmp_path, monkeypatch, **overrides)} + + +def test_without_an_allowlist_every_matching_rule_reports(tmp_path, monkeypatch): + reported = _scan(tmp_path, monkeypatch, javascript_enabled_rules="") + assert {"js-code-injection-eval", "js-weak-hash-md5", "js-debugger-statement"} <= reported + + +def test_allowlist_limits_findings_to_enabled_rules(tmp_path, monkeypatch): + reported = _scan( + tmp_path, + monkeypatch, + javascript_enabled_rules="js-code-injection-eval,js-weak-hash-md5", + all_rules_enabled="false", + ) + assert reported == {"js-code-injection-eval", "js-weak-hash-md5"} + + +def test_all_rules_enabled_overrides_the_allowlist(tmp_path, monkeypatch): + reported = _scan( + tmp_path, + monkeypatch, + javascript_enabled_rules="js-code-injection-eval", + all_rules_enabled="true", + ) + assert "js-debugger-statement" in reported + + +@pytest.mark.parametrize("read_only", [False, True]) +def test_filtered_findings_keep_their_unfiltered_fingerprints(tmp_path, monkeypatch, read_only): + options = {} + if read_only: + rules_dir = tmp_path / "installed rules" + rules_dir.mkdir() + bundled_file = Path(__file__).resolve().parents[1] / "socket_basics/rules/javascript_typescript.yml" + shutil.copyfile(bundled_file, rules_dir / bundled_file.name) + rules_dir.chmod(0o555) + options["opengrep_rules_dir"] = str(rules_dir) + + enabled = "js-code-injection-eval,js-weak-hash-md5" + try: + unfiltered = _scan_findings(tmp_path, monkeypatch, javascript_enabled_rules="", **options) + first = _scan_findings(tmp_path, monkeypatch, javascript_enabled_rules=enabled, **options) + second = _scan_findings(tmp_path, monkeypatch, javascript_enabled_rules=enabled, **options) + finally: + if read_only: + rules_dir.chmod(0o755) + kept = {(rule, fp) for rule, fp in unfiltered if rule in enabled.split(",")} + assert kept and first == kept and second == kept + + +def test_c_and_cpp_allowlists_apply_to_their_own_files(tmp_path, monkeypatch): + rules_dir = tmp_path / "rules" + rules_dir.mkdir() + rules = [ + {"id": rule, "languages": ["c", "cpp"], "pattern": f"{rule}()", "message": rule, "severity": "INFO"} + for rule in ("first", "second") + ] + (rules_dir / "c_cpp.yml").write_text(json.dumps({"rules": rules}), encoding="utf-8") + files = {f"example.{ext}": "void main() { first(); second(); }" for ext in ("c", "cpp")} + options = { + "opengrep_rules_dir": str(rules_dir), + "javascript_sast_enabled": False, + "c_sast_enabled": True, + "cpp_sast_enabled": True, + } + + unfiltered = _run_scan(tmp_path, monkeypatch, files, **options) + assert {(path, rule) for path, rule, _ in unfiltered} == { + (path, rule) for path in files for rule in ("first", "second") + } + c_only = _run_scan(tmp_path, monkeypatch, files, c_enabled_rules="first", **options) + assert c_only == {finding for finding in unfiltered if finding[:2] != ("example.c", "second")} + both = _run_scan( + tmp_path, monkeypatch, files, c_enabled_rules="first", cpp_enabled_rules="second", **options + ) + expected = {("example.c", "first"), ("example.cpp", "second")} + assert both == {finding for finding in unfiltered if finding[:2] in expected}