Skip to content

ci: add semgrep and ast-grep rules - #416

Merged
uniqueg merged 11 commits into
devfrom
ci/static-analysis-rules
Oct 23, 2026
Merged

uniqueg merged 11 commits into
devfrom
ci/static-analysis-rules

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #400 (by hand after the merge, as dev isn't the default branch).

Adds project-specific static analysis rules, as Cloud Registry has them, wired into pre-commit and the lint job:

  • semgrep (.semgrep/foca.yml, security issues that ruff's bandit rules miss):
    • flask-debug-enabled and jwt-decode-without-verification, shared with Cloud Registry. Their messages and severities match, and paths are per repository (FOCA: all YAML files outside tests/). This PR extends their patterns after review (see Follow-up): debug: 1, decode_complete(), jwt.PyJWT().decode(), and options in variables or dict().
    • New: jwt-decode-unsafe-algorithms (none, or the algorithm from the unverified header), yaml-unsafe-load (unsafe_load, full_load, load_all with 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.load and verify=False arguments are already covered by ruff, so no duplicates.
    • Rule tests in .semgrep/foca.py and .semgrep/foca.test.yaml.
    • A .semgrepignore replaces semgrep's defaults, which skip tests/, so that CI and pre-commit check the same files.
  • ast-grep (.ast-grep/, sgconfig.yml), each rule with tests:
    • pydantic-v1-dict and string-status-code, identical to Cloud Registry.
    • New, for logging and exceptions in the package: root-logger-call, print-call (foca/**) and generic-exception-raised (foca/**).
    • Cloud Registry's foca-config-attribute is not adopted: FOCA implements get_config() itself.
  • Pinning: ast-grep in requirements/lint.txt (dev extra ast-grep-cli>=0.51 for the local pre-commit hooks). semgrep in a new requirements/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.
  • Findings on dev: one # nosemgrep comment in foca/security/auth.py sat 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 # nosemgrep that no rule needed is removed. These are comment-only changes, so coverage is unchanged.
  • Docs: "Development" and "Python guidelines" in 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.
  • Checked that the scoping works: a temporary print() or generic raise Exception in foca/ is flagged and the same in tests/ is not. debug: true in examples/petstore/config.yaml is flagged and test configs are not.
  • The version-check step was run locally: it passes, and it fails on a mismatched semgrep pin.
  • ruff check, ruff format --check, mypy, mkdocs build --strict: passed.
  • Reviewed with the adversarial-reviewer and quality-reviewer subagents (two rounds of adversarial review). Medium findings were fixed: CI skipped tests/, and the JWT rules missed decode_complete(), options in variables and algorithms from a stored header.
  • After Sourcery's review: JWT and TLS rules also match falsey 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.
  • CI on 59466d4 (after merging dev with 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-code doesn'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-enabled doesn't match flow style (server: {debug: true}). The pattern is shared with Cloud Registry and FOCA configs use block style.
  • flask-debug-enabled applies to all YAML files outside tests/, so a non-FOCA debug: true key would be flagged too. This is deliberate: suppress it with # nosemgrep: flask-debug-enabled and a reason.
  • The ast-grep version of the pre-commit hook (dev extra, lower bound) can differ from CI's pin. This is accepted and documented in requirements/lint.txt.
  • Indirect forms that would need taint mode are not matched: alg = header["alg"] used later, session.verify set from a variable that is False (Sourcery), None or 0.0 as falsey values, verify=0 on session methods, an options variable reassigned to a safe value (a false positive), and a stored root logger (log = logging.getLogger()).
  • Sourcery: move the registry suppression in foca/security/auth.py to the jwt.decode( line. The registry rule unverified-jwt-decode reports at the options= line; checked with --config p/python (moved: 1 finding, as is: 0).
  • Path scoping (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

  • Cloud Registry should adopt the extended patterns of jwt-decode-without-verification and flask-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:

  • Add project-specific Semgrep security rules for unsafe JWT handling, YAML loading, TLS verification, and enabled Flask debug mode.
  • Add ast-grep rules for generic exceptions, direct printing, root-logger usage, legacy Pydantic serialization, and string HTTP status codes.

Bug Fixes:

  • Correct and clarify existing Semgrep suppressions for intentionally unverified JWT processing and safe authentication logging.

Enhancements:

  • Integrate Semgrep and ast-grep scanning and rule tests into pre-commit and CI, with consistent file scoping and dedicated rule test suites.

Build:

  • Pin Semgrep separately from the project dependencies and add ast-grep to development tooling because of dependency compatibility requirements.

CI:

  • Validate Semgrep and ast-grep hook versions and run both scanners and their rule tests in the lint job.

Documentation:

  • Document the new static analysis checks, local setup, suppression guidance, and Semgrep installation requirements in the contributor documentation.

Tests:

  • Add comprehensive Semgrep and ast-grep rule fixtures covering detected anti-patterns and accepted cases.

Chores:

  • Configure Semgrep ignore behavior and Dependabot updates for the new analysis dependencies.

uniqueg and others added 7 commits October 23, 2026 00:26
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]>
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces 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

Change Details Files
Adds Semgrep security rules and integrates scanning and rule tests into local hooks and CI.
  • Detects unsafe JWT decoding, weak JWT algorithms, unsafe PyYAML loaders, disabled TLS verification, and enabled Flask debug mode.
  • Adds focused Python and YAML rule fixtures, plus a .semgrepignore to align CI and pre-commit scope.
  • Installs Semgrep in an isolated CI environment and validates its pin against the pre-commit hook.
  • Corrects intentional Semgrep suppressions for verified-later JWT processing and credential-safe logging.
.semgrep/foca.yml
.semgrep/foca.py
.semgrep/foca.test.yaml
.semgrepignore
.pre-commit-config.yaml
.github/workflows/checks.yml
requirements/semgrep.txt
foca/security/auth.py
Adds ast-grep anti-pattern rules for Python code and enforces them through development tooling and CI.
  • Flags Pydantic v1 .dict(), string HTTP status codes, root logger calls, package print() calls, and generic exceptions.
  • Scopes package-specific rules to foca/** while allowing tests and examples to retain permitted patterns.
  • Adds rule tests and configures ast-grep scanning and tests in pre-commit and the lint workflow.
  • Adds the ast-grep CLI to development dependencies and pins it with the lint requirements.
.ast-grep/rules/generic-exception-raised.yml
.ast-grep/rules/print-call.yml
.ast-grep/rules/pydantic-v1-dict.yml
.ast-grep/rules/root-logger-call.yml
.ast-grep/rules/string-status-code.yml
.ast-grep/rule-tests/
sgconfig.yml
pyproject.toml
requirements/lint.txt
.pre-commit-config.yaml
.github/workflows/checks.yml
Updates contributor documentation and dependency automation for the new static-analysis checks.
  • Documents installation, execution, version synchronization, and suppression conventions for Semgrep and ast-grep.
  • Adds Dependabot grouping for the separately pinned Semgrep dependency.
  • Extends the documented pre-commit workflow to include both analyzers.
docs/contributing.md
.github/dependabot.yml

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0aae032) to head (05105e4).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #416   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2777      2777           
=========================================
  Hits          2777      2777           
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 23, 2026 00:17

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread .semgrep/foca.yml Resolved
Comment thread .semgrep/foca.yml Resolved
Comment thread .semgrep/foca.yml Resolved
Comment thread .semgrep/foca.yml Resolved
Comment thread .semgrep/foca.yml Resolved
Comment thread foca/security/auth.py Resolved
uniqueg and others added 3 commits October 23, 2026 03:39
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]>
@uniqueg
uniqueg merged commit 600b8cb into dev Oct 23, 2026
22 checks passed
@uniqueg
uniqueg deleted the ci/static-analysis-rules branch October 23, 2026 02:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant