Skip to content

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

Merged
uniqueg merged 5 commits into
devfrom
ci/109-semgrep-ast-grep
Nov 17, 2026
Merged

uniqueg merged 5 commits into
devfrom
ci/109-semgrep-ast-grep

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds project-specific static analysis rules, as in trs-filer, proTES and
cloud-registry, and runs them in pre-commit, so CI's lint job runs them too.

  • semgrep (.semgrep/pro-wes.yml, tests in pro-wes.py and
    pro-wes.test.yaml). These are the security rules shared with FOCA and the
    FOCA apps, the same as trs-filer's apart from paths:
    • flask-debug-enabled
    • jwt-decode-without-verification
    • jwt-decode-unsafe-algorithms
    • yaml-unsafe-load
    • tls-verification-disabled
  • ast-grep (.ast-grep/rules/, .ast-grep/rule-tests/, sgconfig.yml):
    • Ported from trs-filer: foca-config-attribute, generic-exception-raised,
      print-call, pydantic-v1-dict, root-logger-call, string-status-code.
    • Ported from proTES: framework-free-tasks.
    • New for proWES: hard-coded-url, which flags string literals in pro_wes/
      that start with a URL. Docstrings are exempt. Backends must come from the
      config.
    • The review led to wider patterns:
      • string-status-code now also catches tuples in parentheses and prefixed
        literals.
      • root-logger-call now also catches logging.root, getLogger(name=None)
        and getLogger("root").
  • Wiring:
    • The semgrep hooks (scan, plus rule tests when .semgrep/ changes) are
      the same as trs-filer's.
    • The local ast-grep hooks are scan and test.
    • ast-grep-cli is now a dev dependency, and uv.lock is updated.
    • Sourcery skips the rule tests, which contain findings on purpose.
  • Findings:
    • Fixed: POST /service-info returned its status code as the string "201".
      It now returns the integer, and a new test of the controller checks it.
    • Justified with inline suppressions, each with its reason on the line before:
  • Docs: CONTRIBUTING.md gains the section "Static analysis rules". It lists
    the 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-files passed for all hooks, including semgrep, the
    semgrep 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 new test_post_service_info_status_code.
    It failed with '201' != 201 before the fix.
  • Rule scoping, checked by hand: with violations planted in pro_wes/, the
    package-scoped rules flag them. In tests/ they are not flagged.
  • CI: all checks passed (run 44065813126), including Lint with the new hooks.

Declined review findings

  • tls-verification-disabled misses session.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; an alg value pulled out of the header into a
    variable). These are declined here for the same reason and are included in
    the follow-up.
  • Sourcery's opengrep findings in .semgrep/pro-wes.py (8): these lines
    are test inputs that contain the flagged patterns on purpose, and the file
    is never run. .sourcery.yaml now ignores the rule tests. Sourcery reads
    that file from the base branch, though, so the "Sourcery review" check can
    still fail on this PR.
  • The scan hooks don't re-run on commits that change only rules (low):
    this is the same as trs-filer. CI runs --all-files, and CONTRIBUTING.md
    asks contributors to run pre-commit run --all-files before opening a PR.
  • Test POST /service-info through the HTTP client as well (low): the
    direct controller test matches the other controller tests. Connexion 2
    accepts the (None, 201, None) tuple, and the Smoke test job exercises the
    served app.

Open questions

None

🤖 Generated with Claude Code

uniqueg and others added 5 commits November 17, 2026 10:28
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]>
@uniqueg uniqueg self-assigned this Nov 17, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026

Copy link
Copy Markdown

Reviewer's Guide

API

Return the service-info creation status as an integer so the controller’s response matches the expected HTTP status-code type.

  • pro_wes/ga4gh/wes/controllers.py L32, L46

Implementation

Keep the existing Flask and Werkzeug dependencies temporarily with documented suppressions, and suppress the hard-coded backend URL until backends are configurable.

  • pro_wes/ga4gh/wes/workflow_runs.py L10-13, L18-21, L90-91

Configuration

Add the Semgrep security rules and configure their scan and test hooks in pre-commit.

  • .pre-commit-config.yaml L3, L25-47
  • .semgrep/pro-wes.yml L1-118

Add the ast-grep anti-pattern rules and configure the rule directory and pre-commit scan and test hooks.

  • .ast-grep/rules/foca-config-attribute.yml L1-13
  • .ast-grep/rules/framework-free-tasks.yml L1-37
  • .ast-grep/rules/generic-exception-raised.yml L1-17
  • .ast-grep/rules/hard-coded-url.yml L1-19
  • .ast-grep/rules/print-call.yml L1-12
  • .ast-grep/rules/pydantic-v1-dict.yml L1-9
  • .ast-grep/rules/root-logger-call.yml L1-21
  • .ast-grep/rules/string-status-code.yml L1-18
  • .pre-commit-config.yaml L69-81
  • sgconfig.yml L1-6

Run the new analysis checks in CI and add ast-grep to the development dependencies.

  • .github/workflows/ci.yml L104-106
  • pyproject.toml L122

Exclude rule-test fixtures, which intentionally contain findings, from Sourcery review.

  • .sourcery.yaml L15-19

Documentation

Document the rules, their tests, how to run and extend them, and how to suppress findings; link to the guidance from the README.

  • CONTRIBUTING.md L92-145
  • README.md L241-245

Tests

Add Semgrep fixtures covering the security rules’ finding and non-finding cases.

  • .semgrep/pro-wes.py L1-117
  • .semgrep/pro-wes.test.yaml L1-17

Add ast-grep fixtures for valid and invalid examples of each anti-pattern rule.

  • .ast-grep/rule-tests/foca-config-attribute-test.yml L1-6
  • .ast-grep/rule-tests/framework-free-tasks-test.yml L1-18
  • .ast-grep/rule-tests/generic-exception-raised-test.yml L1-9
  • .ast-grep/rule-tests/hard-coded-url-test.yml L1-19
  • .ast-grep/rule-tests/print-call-test.yml L1-7
  • .ast-grep/rule-tests/pydantic-v1-dict-test.yml L1-7
  • .ast-grep/rule-tests/root-logger-call-test.yml L1-15
  • .ast-grep/rule-tests/string-status-code-test.yml L1-13

Test the service-info controller’s integer status-code response and persisted service information.

  • tests/ga4gh/wes/endpoints/test_service_info.py L12, L105-121

Lock files and vendored code

Update the generated dependency lock file to include the new ast-grep development dependency.

  • uv.lock L196-210, L1528, L1542

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 Nov 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.55%. Comparing base (8285d40) to head (160f7db).

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.
📢 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 November 17, 2026 10:35
@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026

Copy link
Copy Markdown

Linked issues

Checked at commit 160f7db

#109 ci: add semgrep and ast-grep rules · 3 of 4 met

# Requirement Status Notes
1 Port applicable rules with tests and add useful proWES-specific rules, including TLS verification and hard-coded URLs. 🟡 Partly met The rules and tests are added, including the hard-coded URL rule, but the TLS rule does not cover session.get(..., verify=False).
2 Run the rules through pre-commit and CI, and have the ast-grep tests pass. ✅ Met The hooks are configured in pre-commit, including rule-test hooks; the PR verification reports the tests and CI checks passed.
3 Fix or justify all findings. ✅ Met The status code finding is fixed; the remaining framework-import and hard-coded-backend findings have inline suppressions with reasons.
4 Document the rules and how to suppress a finding. ✅ Met CONTRIBUTING.md lists the rules and explains rule tests, scoping, and suppressions.

@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 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, 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. (link)
  • 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. (link)
  • 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. (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


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

Comment thread .semgrep/pro-wes.yml Resolved
Comment thread .semgrep/pro-wes.yml Resolved
Comment thread .semgrep/pro-wes.yml Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
Comment thread .semgrep/pro-wes.py Resolved
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.

ci: add semgrep and ast-grep rules

1 participant