Skip to content

style: adopt the shared ruff rule set - #162

Merged
uniqueg merged 6 commits into
devfrom
style/shared-ruff-rules
Oct 21, 2026
Merged

uniqueg merged 6 commits into
devfrom
style/shared-ruff-rules

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adopts the ruff standard decided for all repos, so FOCA and its apps lint the same way.

  • [tool.ruff.lint] selects B C4 D E F G I PL RUF S SIM UP W, which is FOCA's set plus G and S. D applies everywhere, including tests and the docs hooks. Line length stays 88.
  • Ignores, each with a reason comment: FOCA's complexity limits (PLR0912, PLR0913, PLR0915, PLR0917) and PLR2004 (HTTP status codes and other literals). B010 isn't needed. S101 in tests now has a reason too.
  • Fixed the new findings without changing behaviour:
    • SIM117: single with statements in test_server.py
    • PLW2901: no reassigned loop variables in docs/hooks.py and test_app.py
    • RUF005: unpacking instead of list concatenation in test_chart.py, and a GIT_CONFIG list in test_version.py
    • RUF001: fullwidth digits in test_utils.py written as escapes
  • Removed the six type: ignore comments by adding explicit checks:
    • exceptions.problem() raises ValueError for exceptions without a code or description. All callers pass werkzeug exceptions that have both.
    • permissions._require_subject() raises Unauthorized without a subject (in add_owner, remove_owner, getMe).
    • _api_base_path() raises RuntimeError for requests that aren't routed through an API blueprint; this was a KeyError before, and both end as a 500.
    • The documented noqa: S108 in gunicorn_config.py stays.
  • Review fix: is_admin() without a subject no longer checks the subject <prefix>None. Before, if a user named None was an admin, requests without a subject counted as admin. There is a test for this.
  • docs/contributing.md describes the rule set and prefers explicit checks to suppressions.

Behaviour notes (edge cases only):

  • If a deployment sets security.access_control.claim_identity to a claim its tokens lack, POST /services now returns 401 instead of 400 (FOCA's "Subjects must not be empty"), and GET /me returns 401 instead of looking up <prefix>None. The default config doesn't hit this, as FOCA's auth requires the identity claim.

mypy compared with FOCA (for the FOCA follow-up "adopt the shared ruff standard"): cloud-registry checks files = [cloud_registry, docs/hooks.py, tests] with disallow_untyped_defs, disallow_any_generics and warn_unused_ignores, and ignores missing imports per module (Connexion, Gunicorn). FOCA sets only ignore_missing_imports = true globally. FOCA also uses line length 79 and excludes D for docs, examples and tests.

Closes #149

Verification

  • coverage run --source=cloud_registry -m pytest -p no:warnings (with Helm): 766 passed; coverage 100%
  • ruff check . (ruff 0.17.1, as pinned in pre-commit), ruff format --check ., mypy, ast-grep scan: pass
  • mkdocs build --strict: pass
  • git grep "type: ignore" -- '*.py': no matches
  • CI: all checks pass (pre-commit incl. ruff, tests on 3.10 and 3.12, Helm, docs, Docker Compose, codecov patch/project, Read the Docs)

Declined review findings

  • quality-reviewer (low): fall back to exc.code or 500 in problem() instead of raising. Declined: an explicit error is preferred to a silent default, and production callers always pass complete exceptions.
  • quality-reviewer (low): the adapted/declared renames add indirection. Kept, since they are the minimal PLW2901 fixes.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Adopt the shared Ruff standard while replacing type suppressions with explicit validation and correcting authentication edge cases.

Bug Fixes:

  • Prevent requests without an authenticated subject from being treated as the user None and return explicit authentication errors for protected operations.
  • Reject incomplete HTTP exceptions and requests outside API blueprints with explicit errors instead of relying on type suppressions.

Enhancements:

  • Adopt the shared Ruff rule set across application, tests, and documentation hooks, including documented justified exceptions.
  • Update code and tests to satisfy the expanded linting rules without changing intended behavior.
  • Document the shared linting standards and preference for explicit validation over suppression comments.

Documentation:

  • Document the shared Ruff rule set and linting guidance for contributors.

Tests:

  • Add coverage for missing-subject authorization, admin checks involving a None-named user, invalid problem exceptions, and API base-path access outside an API request.

uniqueg and others added 4 commits October 21, 2026 23:52
Lint with the rule set shared with FOCA (B C4 D E F G I PL RUF S SIM UP
W), ignoring FOCA's complexity limits and magic-value comparisons, each
with its reason. Fix the new findings: single with statements, no
reassigned loop variables, unpacking instead of list concatenation, and
fullwidth digits in a test written as escapes. Describe the rules in the
contributing guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Instead of suppressing mypy's optional-type errors, check the values:
problem() rejects exceptions without a code or description, operations
that need the request's subject raise Unauthorized without one, and the
API base path requires a request routed through an API's blueprint.
Behavior is unchanged for requests the API handles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Requests without a subject no longer look up the subject "<prefix>None",
which a user with that identifier could match; only their groups count.

Also from the reviews: say how the rule set differs from FOCA's and why
tests may assert, test all operations that require a subject and both
cases of problem() without a code or description, match the error of
the API base path, and list the Git options of the version test once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Grant the role admin to the user None in the test of requests without a
subject, which passed with the previous is_admin(), too. Also rename the
test of incomplete exceptions, avoid shadowing in is_admin(), and tidy
the wording of the ruff comments.

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

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adopts the shared Ruff configuration and brings the codebase into compliance through targeted, behavior-preserving fixes. It also removes all Python type: ignore comments by adding explicit validation for incomplete exceptions, unauthenticated subjects, and non-API requests, with tests covering the new error paths and the corrected admin edge case.

Sequence diagram for explicit authentication checks

sequenceDiagram
    participant Client
    participant Permissions
    participant Auth
    participant Registry

    Client->>Permissions: add_owner(serviceId)
    Permissions->>Auth: get_current_subject()
    alt subject is missing
        Auth-->>Permissions: None
        Permissions-->>Client: Unauthorized
    else subject is present
        Auth-->>Permissions: user_id
        Permissions->>Registry: add_resource_role(user_id, owner)
        Registry-->>Client: success
    end
Loading

Sequence diagram for validated problem responses

sequenceDiagram
    participant Handler
    participant Exceptions
    participant Response

    Handler->>Exceptions: problem(exc)
    alt code or description is missing
        Exceptions-->>Handler: ValueError
    else exception is complete
        Exceptions->>Response: _response(title, status, detail)
        Response-->>Handler: Problem details response
    end
Loading

Flow diagram for API base path validation

flowchart LR
    Request["Current request"] --> Blueprint{"request.blueprint is set?"}
    Blueprint -->|No| RuntimeError["Raise RuntimeError"]
    Blueprint -->|Yes| BasePath["Return blueprint URL prefix"]
Loading

File-Level Changes

Change Details Files
Standardize Ruff linting across the project and document the shared policy.
  • Expanded the selected rules to include comprehensions, Pylint, Ruff-specific, simplify, logging, security, and docstring checks.
  • Added commented exceptions for accepted complexity and literal-value findings, while documenting the policy and suppression guidance.
  • Applied docstring enforcement consistently to tests and documentation hooks.
  • Fixed newly reported lint findings without changing behavior.
pyproject.toml
docs/contributing.md
docs/hooks.py
tests/ga4gh/registry/test_server.py
tests/test_app.py
tests/test_chart.py
tests/test_utils.py
tests/test_version.py
Replace type-check suppressions with explicit runtime validation and typed control flow.
  • Validate that problem responses receive exceptions with both status codes and descriptions, raising ValueError otherwise.
  • Require an authenticated subject for ownership and current-user operations, raising Unauthorized when absent.
  • Guard API base-path lookup for requests outside an API blueprint with RuntimeError.
  • Remove the None-subject admin lookup edge case and add regression coverage.
cloud_registry/exceptions.py
cloud_registry/ga4gh/registry/permissions.py
tests/test_access_control.py
tests/test_exceptions.py

Assessment against linked issues

Issue Objective Addressed Explanation
#149 Adopt the shared Ruff rule set across the project, including tests and documentation hooks, while retaining an 88-character line length and Ruff formatting. ✅
#149 Resolve new lint findings and remove the six type-ignore suppressions with explicit checks, while documenting all remaining ignores and keeping behavior unchanged apart from appropriate handling of missing request subjects. ✅
#149 Compare cloud-registry's mypy settings with FOCA's and document the differences for the FOCA follow-up. ✅

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 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (72b2b21) to head (26db11f).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #162   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           11        11           
  Lines          868       880   +12     
=========================================
+ Hits           868       880   +12     

☔ 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 21, 2026 22:14

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="tests/test_exceptions.py" line_range="131" />
<code_context>
+
+
[email protected](
+    "exc", [HTTPException(), _NoDescription()], ids=["no_code", "no_description"]
+)
+def test_problem_incomplete_exception(exc: HTTPException) -> None:
</code_context>
<issue_to_address>
**No-code exceptions evade test**

When the code check in `problem()` is removed while the description check remains, `test_problem_incomplete_exception` line 131 uses `HTTPException()` with both `code` and `description` absent, so a description-only check still raises `ValueError` and the test passes even though a no-code exception with a description would be accepted.

Give the no-code test case a nonempty description so it verifies that a missing code alone raises `ValueError`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and requests without a subject now receive Unauthorized for owner-management and getMe operations, and a missing subject can no longer match an admin role named with None. If that behavior is wrong, it can deny access to those operations; reverting restores the previous behavior, and the diff does not introduce an irreversible side effect.

Blocking findings: tests/test_exceptions.py:131


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

Comment thread tests/test_exceptions.py Resolved
uniqueg and others added 2 commits October 22, 2026 00:17
So that the test fails if problem() checks only the description (review
finding of Sourcery).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 185389b into dev Oct 21, 2026
12 checks passed
@uniqueg
uniqueg deleted the style/shared-ruff-rules branch October 21, 2026 22:28
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.

style: adopt the shared ruff rule set

1 participant