Repository navigation
ci: add semgrep and ast-grep rules - #147
Conversation
Mark the Flask and Werkzeug imports of workflow_runs.py and the hard-coded WES backend with ast-grep suppressions and their reasons: the request is read in the controllers with the gateway architecture (#117), and backends become configurable with #118. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Port the static analysis rules of trs-filer and proTES, with their tests, and run them in pre-commit and hence in CI's lint job: - semgrep (.semgrep/pro-wes.yml): flask-debug-enabled, jwt-decode-without-verification, jwt-decode-unsafe-algorithms, yaml-unsafe-load, tls-verification-disabled (shared with FOCA) - ast-grep (.ast-grep/, sgconfig.yml): foca-config-attribute, framework-free-tasks, generic-exception-raised, print-call, pydantic-v1-dict, root-logger-call, string-status-code, and the new hard-coded-url (URLs in string literals of the package) ast-grep-cli becomes a dev dependency; Sourcery skips the rule tests. CONTRIBUTING.md lists the rules and how to suppress a finding. Closes #109 Co-Authored-By: Claude Opus 5.5 <[email protected]>
POST /service-info returned its status code as the string "201". Return the integer, as the ast-grep rule string-status-code requires (it now also detects returned tuples in parentheses), with a test of the controller. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- string-status-code: also returned tuples in parentheses - root-logger-call: also logging.root and getLogger(name=None) - hard-coded-url: more test cases (triple quotes, bare strings) - Notes, comments and CONTRIBUTING.md fitted to proWES; the docs say that rule scoping is untested and where the reason of a suppression goes Co-Authored-By: Claude Opus 5.5 <[email protected]>
- root-logger-call: also getLogger("root"), the root logger since
Python 3.9
- string-status-code: also prefixed string literals (e.g., f"201")
- Rewrap a rule note and clarify the `uv run` hint in CONTRIBUTING.md
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAPIReturn the service-info creation status as an integer so the controller’s response matches the expected HTTP status-code type.
ImplementationKeep the existing Flask and Werkzeug dependencies temporarily with documented suppressions, and suppress the hard-coded backend URL until backends are configurable.
ConfigurationAdd the Semgrep security rules and configure their scan and test hooks in pre-commit.
Add the ast-grep anti-pattern rules and configure the rule directory and pre-commit scan and test hooks.
Run the new analysis checks in CI and add ast-grep to the development dependencies.
Exclude rule-test fixtures, which intentionally contain findings, from Sourcery review.
DocumentationDocument the rules, their tests, how to run and extend them, and how to suppress findings; link to the guidance from the README.
TestsAdd Semgrep fixtures covering the security rules’ finding and non-finding cases.
Add ast-grep fixtures for valid and invalid examples of each anti-pattern rule.
Test the service-info controller’s integer status-code response and persisted service information.
Lock files and vendored codeUpdate the generated dependency lock file to include the new ast-grep development dependency.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #147 +/- ##
==========================================
+ Coverage 80.97% 81.55% +0.57%
==========================================
Files 16 16
Lines 694 694
==========================================
+ Hits 562 566 +4
+ Misses 132 128 -4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 160f7db #109 ci: add semgrep and ast-grep rules · 3 of 4 met
|
There was a problem hiding this comment.
Hey - I've found 8 security issues, and 3 other issues
Security issues:
- Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
- Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
- Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
- Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
- Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
- Detected a possible YAML deserialization vulnerability.
yaml.unsafe_load,yaml.Loader,yaml.CLoader, andyaml.UnsafeLoaderare all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Useyaml.safe_loadoryaml.SafeLoaderinstead. (link) - Detected a possible YAML deserialization vulnerability.
yaml.unsafe_load,yaml.Loader,yaml.CLoader, andyaml.UnsafeLoaderare all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Useyaml.safe_loadoryaml.SafeLoaderinstead. (link) - Detected a possible YAML deserialization vulnerability.
yaml.unsafe_load,yaml.Loader,yaml.CLoader, andyaml.UnsafeLoaderare all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Useyaml.safe_loadoryaml.SafeLoaderinstead. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path=".semgrep/pro-wes.yml" line_range="32" />
<code_context>
+ # `False` or `0`, which PyJWT treats alike
+ patterns:
+ - pattern-either:
+ - pattern: '$JWT.$DECODE(..., options={..., "verify_signature": False, ...}, ...)'
+ - pattern: '$JWT.$DECODE(..., options={..., "verify_signature": 0, ...}, ...)'
+ - pattern: "$JWT.$DECODE(..., options=dict(..., verify_signature=False, ...), ...)"
</code_context>
<issue_to_address>
**Null option disables JWT verification**
When a decode call passes `options={"verify_signature": None}`, `jwt-decode-without-verification` matches `False` and `0` but not `None`; PyJWT 2.15.1 treats a falsey `verify_signature` option as disabling signature verification, so this decode passes the security scan without verifying the token.
Add patterns and rule tests for `verify_signature=None` in both inline options and assigned options.
</issue_to_address>
### Comment 2
<location path=".semgrep/pro-wes.yml" line_range="79-86" />
<code_context>
+ - pattern: $JWT.$DECODE(..., algorithms=jwt.get_unverified_header(...)[...], ...)
+ - pattern: $JWT.$DECODE(..., algorithms=jwt.get_unverified_header(...).get(...), ...)
+ - patterns:
+ - pattern-inside: |
+ $HEADER = jwt.get_unverified_header(...)
+ ...
+ - pattern-either:
+ - pattern: $JWT.$DECODE(..., algorithms=[..., $HEADER[...], ...], ...)
+ - pattern: $JWT.$DECODE(..., algorithms=[..., $HEADER.get(...), ...], ...)
+ - pattern: $JWT.$DECODE(..., algorithms=$HEADER[...], ...)
+ - pattern: $JWT.$DECODE(..., algorithms=$HEADER.get(...), ...)
+ - metavariable-regex:
+ metavariable: $DECODE
</code_context>
<issue_to_address>
**Extracted JWT algorithm passes unchecked**
When code extracts the token header’s `alg` into a scalar before passing it as `algorithms`, the `$HEADER` patterns only match a whole header variable when the decoder indexes it or calls `.get()` inline. Once code extracts the header’s `alg` into a separate scalar and passes that scalar in `algorithms`, Semgrep reports no finding and the decoder can trust an algorithm chosen by the token.
Add a pattern or data-flow check for scalar values derived from an unverified header and passed as the allowed algorithm.
</issue_to_address>
### Comment 3
<location path=".semgrep/pro-wes.yml" line_range="118" />
<code_context>
+ pattern-either:
+ - pattern: $SESSION.verify = False
+ - pattern: $SESSION.verify = 0
+ - pattern: requests.$METHOD(..., verify=0, ...)
</code_context>
<issue_to_address>
**Session TLS calls untested**
The issue asks for a rule against disabled TLS verification in HTTP clients. The added TLS rule checks `.verify` assignments and top-level `requests` calls with `verify=0`, but does not cover `session.get(..., verify=False)` or test that case.
</issue_to_address>
### Comment 4
<location path=".semgrep/pro-wes.py" line_range="17" />
<code_context>
jwt.decode(TOKEN, options={"verify_signature": False})
</code_context>
<issue_to_address>
**security (python.jwt.security.unverified-jwt-decode):** Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified.
```suggestion
jwt.decode(TOKEN, options={"verify_signature": True})
```
*Source: opengrep*
</issue_to_address>
### Comment 5
<location path=".semgrep/pro-wes.py" line_range="19" />
<code_context>
jwt.decode(TOKEN, KEY, algorithms=["RS256"], options={"verify_signature": False})
</code_context>
<issue_to_address>
**security (python.jwt.security.unverified-jwt-decode):** Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified.
```suggestion
jwt.decode(TOKEN, KEY, algorithms=["RS256"], options={"verify_signature": True})
```
*Source: opengrep*
</issue_to_address>
### Comment 6
<location path=".semgrep/pro-wes.py" line_range="41" />
<code_context>
jwt_decode(TOKEN, options={"verify_signature": False})
</code_context>
<issue_to_address>
**security (python.jwt.security.unverified-jwt-decode):** Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified.
```suggestion
jwt_decode(TOKEN, options={"verify_signature": True})
```
*Source: opengrep*
</issue_to_address>
### Comment 7
<location path=".semgrep/pro-wes.py" line_range="43" />
<code_context>
pyjwt.decode(TOKEN, options={"verify_signature": False})
</code_context>
<issue_to_address>
**security (python.jwt.security.unverified-jwt-decode):** Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified.
```suggestion
pyjwt.decode(TOKEN, options={"verify_signature": True})
```
*Source: opengrep*
</issue_to_address>
### Comment 8
<location path=".semgrep/pro-wes.py" line_range="44" />
<code_context>
unverified = {"verify_signature": False}
</code_context>
<issue_to_address>
**security (python.jwt.security.unverified-jwt-decode):** Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified.
```suggestion
unverified = {"verify_signature": True}
```
*Source: opengrep*
</issue_to_address>
### Comment 9
<location path=".semgrep/pro-wes.py" line_range="81" />
<code_context>
yaml.unsafe_load("a: 1")
</code_context>
<issue_to_address>
**security (python.lang.security.deserialization.avoid-pyyaml-load):** Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.
```suggestion
yaml.safe_load("a: 1")
```
*Source: opengrep*
</issue_to_address>
### Comment 10
<location path=".semgrep/pro-wes.py" line_range="91" />
<code_context>
yaml.load_all("a: 1", Loader=yaml.UnsafeLoader)
</code_context>
<issue_to_address>
**security (python.lang.security.deserialization.avoid-pyyaml-load):** Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.
```suggestion
yaml.load_all("a: 1", Loader=yaml.UnsafeLoader)
```
*Source: opengrep*
</issue_to_address>
### Comment 11
<location path=".semgrep/pro-wes.py" line_range="95" />
<code_context>
yaml.load_all("a: 1", Loader=yaml.Loader)
</code_context>
<issue_to_address>
**security (python.lang.security.deserialization.avoid-pyyaml-load):** Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.
```suggestion
yaml.load_all("a: 1", Loader=yaml.Loader)
```
*Source: opengrep*
</issue_to_address>Sourcery assessment
Approval pending. 11 findings to address first.
Blocking findings: .semgrep/pro-wes.yml:32, .semgrep/pro-wes.yml:86, .semgrep/pro-wes.yml:118, .semgrep/pro-wes.py:17, .semgrep/pro-wes.py:19, and 6 more
Summary
Adds project-specific static analysis rules, as in trs-filer, proTES and
cloud-registry, and runs them in pre-commit, so CI's
lintjob runs them too..semgrep/pro-wes.yml, tests inpro-wes.pyandpro-wes.test.yaml). These are the security rules shared with FOCA and theFOCA apps, the same as trs-filer's apart from
paths:flask-debug-enabledjwt-decode-without-verificationjwt-decode-unsafe-algorithmsyaml-unsafe-loadtls-verification-disabled.ast-grep/rules/,.ast-grep/rule-tests/,sgconfig.yml):foca-config-attribute,generic-exception-raised,print-call,pydantic-v1-dict,root-logger-call,string-status-code.framework-free-tasks.hard-coded-url, which flags string literals inpro_wes/that start with a URL. Docstrings are exempt. Backends must come from the
config.
string-status-codenow also catches tuples in parentheses and prefixedliterals.
root-logger-callnow also catcheslogging.root,getLogger(name=None)and
getLogger("root")..semgrep/changes) arethe same as trs-filer's.
scanandtest.ast-grep-cliis now a dev dependency, anduv.lockis updated.POST /service-inforeturned its status code as the string"201".It now returns the integer, and a new test of the controller checks it.
workflow_runs.py, until the request isread in the controllers (feat: adopt proTES gateway architecture #117);
CONTRIBUTING.mdgains the section "Static analysis rules". It liststhe rules, explains how to run and add rule tests and how to suppress a
finding, and notes that rule scoping is untested. The README points to it.
Full review lane: two rounds of adversarial and quality review.
Closes #109
Verification
pre-commit run --all-filespassed for all hooks, including semgrep, thesemgrep rule tests (5/5), ast-grep and the ast-grep rule tests (8/8). I
skipped actionlint locally because its download fails in the sandbox; the
only workflow change is a comment.
pytest: 63 passed, including the newtest_post_service_info_status_code.It failed with
'201' != 201before the fix.pro_wes/, thepackage-scoped rules flag them. In
tests/they are not flagged.Declined review findings
tls-verification-disabledmissessession.get(..., verify=False)(medium): the semgrep rules are shared with FOCA, proTES, trs-filer and
cloud-registry and must stay identical. The fix belongs in FOCA first and
is then mirrored to the apps; a follow-up issue is drafted for that.
Sourcery raised the same point, and two more gaps in the shared JWT rules
(
verify_signature: None; analgvalue pulled out of the header into avariable). These are declined here for the same reason and are included in
the follow-up.
.semgrep/pro-wes.py(8): these linesare test inputs that contain the flagged patterns on purpose, and the file
is never run.
.sourcery.yamlnow ignores the rule tests. Sourcery readsthat file from the base branch, though, so the "Sourcery review" check can
still fail on this PR.
this is the same as trs-filer. CI runs
--all-files, andCONTRIBUTING.mdasks contributors to run
pre-commit run --all-filesbefore opening a PR.POST /service-infothrough the HTTP client as well (low): thedirect controller test matches the other controller tests. Connexion 2
accepts the
(None, 201, None)tuple, and the Smoke test job exercises theserved app.
Open questions
None
🤖 Generated with Claude Code