Repository navigation
ci: add semgrep and ast-grep rules - #416
Conversation
The comment was on the line of the options, where semgrep does not apply it to the finding, which starts at the call; move it to the line before the call and name the rule it suppresses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the semgrep rules of Cloud Registry (flask-debug-enabled, for all YAML files outside tests, and jwt-decode-without-verification) and rules for gaps of ruff's bandit rules: jwt-decode-unsafe-algorithms, yaml-unsafe-load and tls-verification-disabled, with rule tests in `.semgrep/`. Add the ast-grep rules pydantic-v1-dict and string-status-code of Cloud Registry, and root-logger-call, print-call and generic-exception-raised for the package, with rule tests. Run them in pre-commit and in the lint job. semgrep is pinned in `requirements/semgrep.txt` (its dependencies conflict with FOCA's, so the lint job installs it in a separate environment), ast-grep in `requirements/lint.txt`; Dependabot updates both, and the lint job checks that the semgrep hook has the pinned version, as for ruff. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: the JWT rules also match `decode_complete()`, `jwt.PyJWT().decode()`, options in variables or `dict()`, algorithm tuples and sets, and algorithms taken from a stored unverified header; yaml-unsafe-load also matches positional and C loaders; flask-debug-enabled also matches `debug: 1`; root-logger-call also matches `logging.getLogger().<method>()`. Add test cases for each. Add a `.semgrepignore`, as semgrep's default one skips `tests/` in CI, while pre-commit passes those files to semgrep, so both now check the same files. Clarify which parts of the shared rules must stay identical. Co-Authored-By: Claude Opus 5.5 <[email protected]>
No semgrep rule of the repository matches the debug log message, and suppressions now name their rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: jwt-decode-without-verification also matches options
built with `dict()` in a variable, root-logger-call also matches
`logging.getLogger(None)` and `logging.getLogger("")`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The bare nosemgrep comments suppressed rules of semgrep's registry (`p/python`), which developers may run in addition to the repository's rules: restore the one of the debug log message and add one for the unverified decoding of the issuer, each naming its rule and reason. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces project-specific Semgrep security checks and ast-grep anti-pattern checks, with tested rules, aligned pre-commit and CI enforcement, isolated Semgrep dependencies, synchronized tool pins, corrected suppressions, and contributor documentation. File-Level Changes
Possibly linked issues
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 #416 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 27 27
Lines 2777 2777
=========================================
Hits 2777 2777
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path=".semgrep/foca.yml" line_range="34" />
<code_context>
+ tokens of callers
+ patterns:
+ - pattern-either:
+ - pattern: '$JWT.$DECODE(..., options={..., "verify_signature": False, ...}, ...)'
+ - pattern: "$JWT.$DECODE(..., options=dict(..., verify_signature=False, ...), ...)"
+ - pattern: "$JWT.$DECODE(..., verify=False, ...)"
</code_context>
<issue_to_address>
**Unsafe imports evade detection**
When package code imports JWT decoders or unsafe YAML loaders directly, including under an alias, the JWT and YAML patterns require qualified calls, so direct calls produce no finding and unsafe token decoding or YAML loading passes CI.
Extend both rules to recognize directly imported functions and their aliases.
Also at `.semgrep/foca.yml:61`, `.semgrep/foca.yml:89-100`.
</issue_to_address>
### Comment 2
<location path=".semgrep/foca.yml" line_range="34" />
<code_context>
+ tokens of callers
+ patterns:
+ - pattern-either:
+ - pattern: '$JWT.$DECODE(..., options={..., "verify_signature": False, ...}, ...)'
+ - pattern: "$JWT.$DECODE(..., options=dict(..., verify_signature=False, ...), ...)"
+ - pattern: "$JWT.$DECODE(..., verify=False, ...)"
</code_context>
<issue_to_address>
**Zero disables JWT signature checks**
When a developer decodes caller-supplied tokens with `options={"verify_signature": 0}`, pyJWT treats `verify_signature=0` as false, so it skips signature verification. `jwt-decode-without-verification` matches only the literal `False` in this option and lets a caller-supplied token be decoded without a finding.
Match falsey values such as `0` in the verification option and add a regression test.
</issue_to_address>
### Comment 3
<location path=".semgrep/foca.yml" line_range="34-36" />
<code_context>
+ tokens of callers
+ patterns:
+ - pattern-either:
+ - pattern: '$JWT.$DECODE(..., options={..., "verify_signature": False, ...}, ...)'
+ - pattern: "$JWT.$DECODE(..., options=dict(..., verify_signature=False, ...), ...)"
+ - pattern: "$JWT.$DECODE(..., verify=False, ...)"
+ - patterns:
+ - pattern-either:
</code_context>
<issue_to_address>
**Aliased JWT calls evade detection**
When code aliases the `jwt` module or imports `get_unverified_header` directly, the stored-header algorithm patterns require the literal `jwt` name, and the decoder patterns require qualified calls, so unsafe decoding of caller-supplied tokens produces no finding.
Update the JWT decoder and header-extraction patterns to recognize aliased modules and directly imported functions.
Also at `.semgrep/foca.yml:67-79`.
</issue_to_address>
### Comment 4
<location path=".semgrep/foca.yml" line_range="107" />
<code_context>
+ message: >-
+ Certificate verification must not be disabled; configure a CA bundle
+ instead (`verify` may name its path)
+ pattern: $SESSION.verify = False
</code_context>
<issue_to_address>
**Zero disables certificate checks**
When code sets Requests certificate verification to `0`, the TLS rule matches only literal `False`, so `verify=0` produces no finding and HTTPS traffic can be intercepted.
Match falsey integer values such as `0` in the Requests verification rule.
</issue_to_address>
### Comment 5
<location path=".semgrep/foca.yml" line_range="107" />
<code_context>
+ message: >-
+ Certificate verification must not be disabled; configure a CA bundle
+ instead (`verify` may name its path)
+ pattern: $SESSION.verify = False
</code_context>
<issue_to_address>
**Configured TLS verification bypasses the rule**
When package code assigns `session.verify` from a variable whose value is `False`, a value such as `verify_tls = False; session.verify = verify_tls` does not match the literal-only pattern, so disabled certificate verification passes CI and requests accepts unverified HTTPS responses.
Add a pattern for locally assigned false values, with a test for a variable-based assignment.
</issue_to_address>
### Comment 6
<location path="foca/security/auth.py" line_range="277" />
<code_context>
token,
- options={"verify_signature": False}, # nosemgrep
+ # Verified later, as above (semgrep's registry rules, `p/python`)
+ # nosemgrep: unverified-jwt-decode
+ options={"verify_signature": False},
)
</code_context>
<issue_to_address>
**Registry suppression misses decode finding**
When developers run Semgrep's registry `unverified-jwt-decode` rule, semgrep applies the `unverified-jwt-decode` suppression to the options line, not the finding that starts at `jwt.decode(`, so the intentional issuer decode remains reported when developers run the registry rule.
Place the named registry-rule suppression immediately before the `jwt.decode(` call.
</issue_to_address>Sourcery assessment
Approval pending. 6 findings to address first.
Blocking findings: .semgrep/foca.yml:34, .semgrep/foca.yml:34, .semgrep/foca.yml:36, .semgrep/foca.yml:107, .semgrep/foca.yml:107, and 1 more
Review findings: PyJWT and requests treat `0` like `False`, so jwt-decode-without-verification also matches `verify_signature` and `verify` set to `0`, and tls-verification-disabled `session.verify = 0` and `verify=0` in requests calls (ruff's S501 flags `False` only). Add rule tests for these and for aliased and directly imported functions, which semgrep's import resolution already matches. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #400 (by hand after the merge, as
devisn't the default branch).Adds project-specific static analysis rules, as Cloud Registry has them, wired into pre-commit and the lint job:
.semgrep/foca.yml, security issues that ruff's bandit rules miss):flask-debug-enabledandjwt-decode-without-verification, shared with Cloud Registry. Their messages and severities match, andpathsare per repository (FOCA: all YAML files outsidetests/). This PR extends their patterns after review (see Follow-up):debug: 1,decode_complete(),jwt.PyJWT().decode(), and options in variables ordict().jwt-decode-unsafe-algorithms(none, or the algorithm from the unverified header),yaml-unsafe-load(unsafe_load,full_load,load_allwith unsafe loaders, which ruff's S506 doesn't flag),tls-verification-disabled(session.verify = False, which ruff's S501 doesn't flag).eval,exec,yaml.loadandverify=Falsearguments are already covered by ruff, so no duplicates..semgrep/foca.pyand.semgrep/foca.test.yaml..semgrepignorereplaces semgrep's defaults, which skiptests/, so that CI and pre-commit check the same files..ast-grep/,sgconfig.yml), each rule with tests:pydantic-v1-dictandstring-status-code, identical to Cloud Registry.root-logger-call,print-call(foca/**) andgeneric-exception-raised(foca/**).foca-config-attributeis not adopted: FOCA implementsget_config()itself.requirements/lint.txt(dev extraast-grep-cli>=0.51for the local pre-commit hooks). semgrep in a newrequirements/semgrep.txt, as its dependencies conflict with FOCA's (wcmatch, via pycasbin); the lint job installs it in a separate environment. Dependabot updates both: semgrep gets its own group like ruff. The lint job now checks that the semgrep hook matches its pin, as it does for ruff.dev: one# nosemgrepcomment infoca/security/auth.pysat on the wrong line and didn't name its rule. It now names the rule, with its reason (the signature is verified later). One bare# nosemgrepthat no rule needed is removed. These are comment-only changes, so coverage is unchanged.docs/contributing.md.How it was verified
pre-commit run --all-files, all hooks including semgrep, semgrep rule tests, ast-grep and ast-grep rule tests: passed.ast-grep test --skip-snapshot-tests: 5/5.cd .semgrep && semgrep --test .: 5/5. A test case flipped on purpose made both the hook and the test fail.semgrep scan --config .semgrep --error: 0 findings on 144 files, tests included.ast-grep scan: 0 findings.print()or genericraise Exceptioninfoca/is flagged and the same intests/is not.debug: trueinexamples/petstore/config.yamlis flagged and test configs are not.ruff check,ruff format --check,mypy,mkdocs build --strict: passed.tests/, and the JWT rules misseddecode_complete(), options in variables and algorithms from a stored header.0; rule tests added for those and for aliased or directly imported functions (already matched by semgrep's import resolution). Focused adversarial re-check: no high or medium findings.devwith the aggregate checks): all checks passed, including Lint, type-check and build, Unit tests, Scan images, codecov and Read the Docs; Sourcery passed with no open threads.Declined review findings
string-status-codedoesn't match parenthesized tuples (return (body, "201")). Not changed, to keep the rule identical to Cloud Registry; ruff format removes such parentheses anyway.flask-debug-enableddoesn't match flow style (server: {debug: true}). The pattern is shared with Cloud Registry and FOCA configs use block style.flask-debug-enabledapplies to all YAML files outsidetests/, so a non-FOCAdebug: truekey would be flagged too. This is deliberate: suppress it with# nosemgrep: flask-debug-enabledand a reason.requirements/lint.txt.alg = header["alg"]used later,session.verifyset from a variable that isFalse(Sourcery),Noneor0.0as falsey values,verify=0on session methods, an options variable reassigned to a safe value (a false positive), and a stored root logger (log = logging.getLogger()).foca/security/auth.pyto thejwt.decode(line. The registry ruleunverified-jwt-decodereports at theoptions=line; checked with--config p/python(moved: 1 finding, as is: 0).files,paths) isn't covered by the rule tests, as neither tool supports that. It was checked by hand (see above) and is noted in.semgrep/foca.yml.Follow-up
jwt-decode-without-verificationandflask-debug-enabled(copy them from.semgrep/foca.yml), so that the shared rules are identical again. They were changed here first because FOCA implements the token checks.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Enforce project-specific security and code-quality rules with Semgrep and ast-grep across local pre-commit checks and CI.
New Features:
Bug Fixes:
Enhancements:
Build:
CI:
Documentation:
Tests:
Chores: