Skip to content

build: run checks with pre-commit - #94

Merged
uniqueg merged 6 commits into
devfrom
chore/tooling
Oct 20, 2026
Merged

uniqueg merged 6 commits into
devfrom
chore/tooling

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Run all static checks with pre-commit, locally and in CI (closes #73, resolves #31).

  • ruff replaces flake8 and black (lint + format, line length 88). Rules: pycodestyle, Pyflakes, isort, bugbear, pyupgrade, bandit (S), logging format (G). The findings are fixed, among them f-strings in logging calls, raise ... from, Dict/Optional → dict/X | None, and the import order. The formatter changes no code.
  • mypy also checks tests/. The blanket ignore_missing_imports is replaced by an override for Connexion 2, which ships no types, and warn_unused_ignores is on. The app now reads its config through typed helpers in cloud_registry/utils.py (get_custom_config(), get_collection(), built on FOCA 0.14's get_config()/get_collection()). That removes the attr-defined ignores. The one left is getServices.__wrapped__, which Refactor: remove duplicated and unused code #74 removes.
  • pre-commit (.pre-commit-config.yaml, hooks pinned to commit SHAs, updated by Dependabot):
    • pre-commit-hooks: YAML syntax, whitespace, merge conflicts, large files. The vendored GA4GH specs are kept as published.
    • ruff, plus mypy and ast-grep from the dev requirements.
    • semgrep with local rules in .semgrep/: Flask debug mode in configs, JWT decoding without verification.
    • gitleaks: staged changes on commit; the whole checkout in CI (--hook-stage manual gitleaks-all).
    • ast-grep (sgconfig.yml, rules and rule tests in .ast-grep/): HTTP status codes as strings, Pydantic v1 .dict(), untyped FOCA config access in the app.
  • CI runs pre-commit instead of the separate flake8/mypy/black steps, and caches the hook environments.
  • README describes the setup and how to suppress false positives.

Verification

  • pytest: 74 passed (Python 3.10, FOCA 0.14.0).
  • ruff check/format, mypy (20 files), ast-grep scan and ast-grep test (3 rules), semgrep (both rules flag planted samples; the repo is clean), gitleaks (working tree and full history: no leaks), check-yaml, pre-commit validate-config.
  • pre-commit run itself could not set up the hook repos locally, because the sandbox proxy blocks it. CI is the first full run.
  • Acceptance criteria:
    • A string status code fails ast-grep (rule test).
    • An f-string in a logging call fails ruff (G004). ruff already covers this, so no ast-grep rule duplicates it.
  • Adversarial and maintainability reviews, 2 rounds each. Fixed:
    • mypy in CI lacked the runtime requirements.
    • Uncommitted utils tests.
    • gitleaks scanning ignored local files on commit.
    • Unanchored semgrep paths.
    • Dependabot coverage for the hook pins.

Notes

  • Python security rules come from ruff's bandit rules and secrets from gitleaks. Semgrep's registry rule sets are not vendored, because their license does not allow redistribution. .semgrep/ therefore holds only project-specific rules.
  • Declined review findings:
    • Splitting the first commit, and .git-blame-ignore-revs entries: this PR is squash-merged, so those commit hashes won't exist on dev.
    • Test files for the two semgrep rules: they were checked against samples instead.
    • Rules covering more patterns: their notes state what they detect.

🤖 Generated with Claude Code

Summary by Sourcery

Centralize local and CI quality checks in a pinned pre-commit configuration while modernizing the codebase to comply with the new linting, typing, and security rules.

New Features:

  • Add pre-commit checks for formatting, linting, type checking, security scanning, and project-specific anti-patterns.
  • Add project-specific Semgrep and ast-grep rules with automated rule tests.

Bug Fixes:

  • Use typed FOCA configuration and collection accessors to eliminate unsafe application configuration access.
  • Update code and configuration to satisfy stricter linting, typing, and security checks.

Enhancements:

  • Replace separate flake8, Black, and mypy CI steps with cached pre-commit checks.
  • Modernize Python typing and Pydantic usage while standardizing code formatting and import ordering.

CI:

  • Run the complete static analysis and security check suite in CI through pre-commit, including full-repository secret scanning.
  • Add Dependabot updates for pinned pre-commit hook revisions.

Documentation:

  • Document local development setup, pre-commit usage, and suppression of legitimate check findings.

Tests:

  • Add unit tests for typed configuration and collection helpers.
  • Add ast-grep rule tests for project-specific anti-patterns.

uniqueg and others added 5 commits October 20, 2026 06:14
Replace flake8 and black with ruff (lint and format, line length 88).
Besides the flake8 rules, ruff checks import order, bugbear, pyupgrade,
bandit (security) and logging format rules; the findings are fixed,
e.g. f-strings in logging calls. Formatting is unchanged.

mypy now checks `tests/` too, and the blanket `ignore_missing_imports`
is replaced by an override for Connexion 2, which has no type
information. The app reads its config and collections through typed
helpers in `cloud_registry.utils` (FOCA 0.14's `get_config()` and
`get_collection()`), so the `attr-defined` ignores are gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove trailing whitespace and blank lines at the end of files, as the
new pre-commit hooks require. Vendored GA4GH specifications are left
as published.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run all static checks with pre-commit, locally on commit and in CI
(`pre-commit run --all-files`), with hooks pinned to commits:

- pre-commit-hooks: YAML syntax, whitespace, merge conflicts, large
  files
- ruff (lint and format) and mypy (installed dev dependencies)
- semgrep with local rules in `.semgrep/`: Flask debug mode in configs,
  JWT decoding without verification
- gitleaks: secrets in the working tree
- ast-grep with rules (and rule tests) in `.ast-grep/`: HTTP status
  codes as strings, Pydantic v1 `.dict()`, untyped FOCA config access
  in the app

f-strings in logging calls are caught by ruff (`G004`). The README
describes the setup.

Resolves #31
Closes #73

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- CI installs the runtime requirements, which mypy needs for imports
- Test `cloud_registry.utils`
- gitleaks scans staged changes on commit and the whole checkout in CI
  (manual stage), so ignored local files do not block commits
- ast-grep runs from the dev requirements, so Dependabot updates it;
  Dependabot also updates the pre-commit hook revisions
- Cache pre-commit environments in CI
- Document the rules' limits and how to suppress findings

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop an assertion that only holds for the unit test config, and
document the manual-stage gitleaks scan that CI runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR replaces separate lint, format, type-check, and security workflows with a pinned pre-commit pipeline used consistently by developers and CI, adds tested project-specific Semgrep and ast-grep rules, and updates the application to use typed FOCA configuration/collection helpers while modernizing Python code for the new checks.

Sequence diagram for CI static checks

sequenceDiagram
    participant CI as CI workflow
    participant Env as Python environment
    participant Cache as Hook environment cache
    participant PC as pre-commit
    participant Hooks as Checks and security hooks
    CI->>Env: Install requirements.txt and requirements_dev.txt
    CI->>Cache: Restore or save pre-commit environments
    CI->>PC: pre-commit run --all-files --show-diff-on-failure
    PC->>Hooks: Run ruff, mypy, ast-grep, semgrep and hygiene hooks
    CI->>PC: pre-commit run --all-files --hook-stage manual gitleaks-all
    PC->>Hooks: Scan the whole checkout for secrets
Loading

Sequence diagram for typed FOCA configuration access

sequenceDiagram
    participant Controller as Registry controller
    participant Utils as cloud_registry.utils
    participant FOCA as FOCA configuration API
    participant Mongo as MongoDB collection
    Controller->>Utils: get_custom_config()
    Utils->>FOCA: get_config()
    FOCA-->>Utils: Typed base configuration
    Utils-->>Controller: CustomConfig
    Controller->>Utils: get_collection(name)
    Utils->>FOCA: get_collection(db, collection)
    FOCA-->>Utils: Collection
    Utils-->>Controller: MongoDB collection
    Controller->>Mongo: find, find_one, insert_one or replace_one
Loading

File-Level Changes

Change Details Files
Unify local and CI quality gates under pinned pre-commit hooks.
  • Replace standalone flake8, Black, and mypy CI steps with pre-commit execution.
  • Add Ruff lint/format, mypy, Semgrep, ast-grep, YAML/whitespace checks, and staged/full-repository gitleaks hooks.
  • Cache hook environments and add Dependabot updates for hook revisions.
  • Document installation, execution, and false-positive suppression workflows.
.pre-commit-config.yaml
.github/workflows/checks.yaml
.github/dependabot.yml
README.md
requirements_dev.txt
Add project-specific static-analysis rules and tests for security and API anti-patterns.
  • Detect enabled Flask debug mode and unverified JWT decoding with Semgrep.
  • Detect string HTTP status codes, Pydantic v1 .dict(), and untyped FOCA configuration access with ast-grep.
  • Add rule configuration and executable valid/invalid rule tests.
.semgrep/cloud-registry.yml
sgconfig.yml
.ast-grep/rules/foca-config-attribute.yml
.ast-grep/rules/pydantic-v1-dict.yml
.ast-grep/rules/string-status-code.yml
.ast-grep/rule-tests/foca-config-attribute-test.yml
.ast-grep/rule-tests/pydantic-v1-dict-test.yml
.ast-grep/rule-tests/string-status-code-test.yml
Modernize linting, typing, and Python code patterns for Ruff and expanded mypy coverage.
  • Replace Black/flake8 configuration with Ruff rules for style, imports, upgrades, bugbear, bandit, and logging.
  • Extend mypy to tests, enable unused-ignore warnings, and scope missing-import suppression to Connexion.
  • Modernize annotations, logging calls, exception chaining, imports, and Pydantic APIs.
pyproject.toml
cloud_registry/app.py
cloud_registry/exceptions.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_info.py
cloud_registry/service_models/custom_config.py
Centralize typed FOCA configuration and database collection access.
  • Introduce helpers backed by FOCA's typed configuration and collection APIs.
  • Replace direct untyped app configuration/database traversal in registry services.
  • Update application fixtures to register configuration through FOCA's supported API.
cloud_registry/utils.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_info.py
tests/conftest.py
tests/test_utils.py
Apply repository-wide formatting and whitespace normalization required by the new checks.
  • Normalize imports, trailing whitespace, end-of-file newlines, and minor formatting across source, tests, documentation, deployment files, and metadata.
Dockerfile
PULL_REQUEST_TEMPLATE.md
cloud_registry/config.yaml
cloud_registry/api/additions.openapi.yaml
deployment/README.md
deployment/templates/cloud-registry-ingress.yaml
deployment/templates/mongo-init-script.yaml
deployment/values.yaml
docs/api/conf.py
docs/api/index.rst
docs/api/requirements.txt
tests/ga4gh/registry/test_server.py
tests/ga4gh/registry/test_service_info.py
tests/test_app.py

Assessment against linked issues

Issue Objective Addressed Explanation
#31 Fix mypy issues caused by untyped FOCA configuration and collection access, removing the corresponding type-ignore annotations. ✅
#31 Improve mypy coverage and ensure obsolete ignore annotations are detected. ✅
#73 Replace Flake8 and Black with Ruff for linting and formatting, keep the 88-character line length, and migrate the existing code to pass the new checks. ✅
#73 Upgrade mypy, check both application and test code, and remove blanket missing-import and type-ignore suppressions where they are no longer needed. ✅
#73 Provide a documented, unified pre-commit workflow used in CI, including security and project-specific anti-pattern checks that reject string HTTP status codes and f-strings in logging calls. ✅

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

@uniqueg
uniqueg marked this pull request as ready for review October 20, 2026 04:48
@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3b016bb) to head (77ce92a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #94   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            6         7    +1     
  Lines          223       225    +2     
=========================================
+ Hits           223       225    +2     

☔ 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.

@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 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path=".semgrep/cloud-registry.yml" line_range="23-24" />
<code_context>
+      tokens of callers
+    patterns:
+      - pattern-either:
+          - pattern: 'jwt.decode(..., options={..., "verify_signature": False, ...}, ...)'
+          - pattern: "jwt.decode(..., verify=False, ...)"
</code_context>
<issue_to_address>
**Unverified JWT calls pass the check**

When code imports `decode` directly from `jwt` and disables signature verification, the patterns only match calls spelled `jwt.decode`, so Semgrep does not report the direct `decode` call and unverified token decoding passes the security check.

Add patterns that also match directly imported `decode` calls with signature verification disabled.
</issue_to_address>

### Comment 2
<location path=".semgrep/cloud-registry.yml" line_range="14" />
<code_context>
+      include:
+        - "/cloud_registry/config.yaml"
+        - "/deployment/**/*.yaml"
+    pattern-regex: (?im)^\s*debug:\s*['"]?(true|yes|on)['"]?\s*$
+  - id: jwt-decode-without-verification
+    languages: [python]
</code_context>
<issue_to_address>
**Debug-enabled configs evade the check**

When an included YAML config sets `debug` to `true`, `yes`, or `on` followed by a trailing comment, the regex requires the truthy value to end the line, so Semgrep misses the setting and passes the debug-enabled config; the Flask debugger’s code-execution risk remains unflagged, including when the app listens on `0.0.0.0`.

Update the regex to allow trailing YAML comments after the truthy value.

Also at `.semgrep/cloud-registry.yml:13`.
</issue_to_address>

### Comment 3
<location path="docs/api/requirements.txt" line_range="4" />
<code_context>
 Sphinx==7.2.6
 readthedocs-sphinx-ext==2.2.3
 sphinx-rtd-theme==1.3.0
-toml==0.10.0
\ No newline at end of file
+toml==0.10.0
</code_context>
<issue_to_address>
**Clean documentation builds lose TOML**

When the documentation environment is installed from `docs/api/requirements.txt` without unrelated packages already installed, `docs/api/conf.py` still imports `toml` and calls `toml.load`, but removing this requirement leaves a clean documentation environment without that module. Sphinx then fails while loading its configuration.

Keep the `toml` requirement or change the configuration to use a parser available in the supported Python versions.
</issue_to_address>

### Comment 4
<location path=".ast-grep/rules/string-status-code.yml" line_range="15" />
<code_context>
+constraints:
+  CODE:
+    kind: string
+    regex: ^["']\d{3}["']$
</code_context>
<issue_to_address>
**String status variables pass the rule**

When an endpoint stores a string status code in a variable and returns that variable in the response tuple, `CODE` must be a string literal matching three digits, so `status = "201"; return body, status` passes the check even though the returned status code is still a string. The rule therefore misses a case its message says it detects.

Add coverage for common string-valued status variables, or clarify that the rule detects only literal string codes.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: .semgrep/cloud-registry.yml:24, .semgrep/cloud-registry.yml:14, docs/api/requirements.txt:4, .ast-grep/rules/string-status-code.yml:15


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

Comment thread .semgrep/cloud-registry.yml Resolved
Comment thread .semgrep/cloud-registry.yml Resolved
Comment thread docs/api/requirements.txt Resolved
Comment thread .ast-grep/rules/string-status-code.yml Resolved
The semgrep rule for Flask debug mode missed values followed by a YAML
comment. Also state that the status code rule detects string literals
only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 3d3d843 into dev Oct 20, 2026
10 checks passed
@uniqueg
uniqueg deleted the chore/tooling branch October 20, 2026 05:00
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.

Tooling: ruff, current mypy, pre-commit, semgrep Bug: Fix mypy ignored cases

1 participant