diff --git a/.codacy.yaml b/.codacy.yaml deleted file mode 100644 index a8feb4081..000000000 --- a/.codacy.yaml +++ /dev/null @@ -1,3 +0,0 @@ ---- -exclude_paths: - - "tests/**" \ No newline at end of file diff --git a/.github/workflows/run-validations.yml b/.github/workflows/run-validations.yml index 2f3b2b4e7..0d256e281 100644 --- a/.github/workflows/run-validations.yml +++ b/.github/workflows/run-validations.yml @@ -1,6 +1,11 @@ name: Validations -on: [push] +on: + push: + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: lint: @@ -14,10 +19,10 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - name: Install Python dependencies and run acceptance tests - run: | - pip3 install --user --ignore-installed -r requirements-dev.txt - flake8 --exclude=scripts/,src/,.cache,.git,.idea,.tox,._trial_temp/,venv/ --ignore F811,E402 + - name: Install Ruff + run: pip3 install --user "ruff==0.17.*" + - name: Ruff lint + run: ruff check . - name: Cancel workflow runs for commit on error if: failure() uses: ./.github/.release/actions/actions/utils/fast-jobs-failure diff --git a/.github/workflows/vulnerability-scan.yml b/.github/workflows/vulnerability-scan.yml new file mode 100644 index 000000000..ef09fc207 --- /dev/null +++ b/.github/workflows/vulnerability-scan.yml @@ -0,0 +1,28 @@ +name: Vulnerability scan +on: + push: + branches: + - master + - main + workflow_dispatch: + +jobs: + security: + name: Snyk dependency scan + runs-on: + group: organization/Default + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Setup Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install SDK dependencies + run: pip3 install --user . + - name: Setup Snyk CLI + uses: snyk/actions/setup@master + - name: Run Snyk monitor for vulnerabilities + run: snyk monitor --org=sdk --file=setup.py + env: + SNYK_TOKEN: ${{ secrets.SNYK_SDK_TOKEN }} diff --git a/DEVELOPER.md b/DEVELOPER.md index acf205ba4..21e1ed9b7 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -24,12 +24,18 @@ This runs `py.test tests --cov=pubnub --ignore=tests/manual/`. ## Linting -CI runs flake8 in `.github/workflows/run-validations.yml`. To run the same check locally: +CI runs Ruff (config in `ruff.toml`) in `.github/workflows/run-validations.yml`. To run the same checks locally: ```sh -flake8 --exclude=scripts/,src/,.cache,.git,.idea,.tox,._trial_temp/,venv/ --ignore F811,E402 +ruff check . ``` +`ruff check` covers the whole repository except `scripts` and `src`. In `tests`, only `E`, `F` and `W` apply. Ruff is pinned to `0.17.*` and runs in preview mode. Enabled rule sets: `E`, `F`, `W` (pycodestyle, Pyflakes), `S` (security, `assert` allowed), `B` (bugbear), `PL` (Pylint), `SIM` (simplify) and `C90` (complexity). Disabled rules are commented in `ruff.toml`; remove baseline entries as they are fixed. Formatting is not checked in CI. + +## Vulnerability scan + +`.github/workflows/vulnerability-scan.yml` runs Snyk on pushes to `master` and `main` to monitor the dependencies declared in `setup.py`. + ## Pull requests - Include tests for behavioral changes and keep the test matrix green on all supported Python versions. diff --git a/bandit.yml b/bandit.yml deleted file mode 100644 index 75d550c32..000000000 --- a/bandit.yml +++ /dev/null @@ -1 +0,0 @@ -skips: ['B101'] diff --git a/examples/pubnub_asyncio_simple/main.py b/examples/pubnub_asyncio_simple/main.py index b7fb893d5..5914b10c6 100644 --- a/examples/pubnub_asyncio_simple/main.py +++ b/examples/pubnub_asyncio_simple/main.py @@ -30,6 +30,7 @@ async def main(pubnub): while True: await asyncio.sleep(1) + if __name__ == "__main__": loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) diff --git a/pubnub/endpoints/access/grant_token.py b/pubnub/endpoints/access/grant_token.py index 35d9ec9b3..7fb6ff52c 100644 --- a/pubnub/endpoints/access/grant_token.py +++ b/pubnub/endpoints/access/grant_token.py @@ -22,7 +22,7 @@ class PNGrantTokenResultEnvelope(Envelope): class GrantToken(Endpoint): - GRANT_TOKEN_PATH = "/v3/pam/%s/grant" + GRANT_TOKEN_PATH = "/v3/pam/%s/grant" # noqa: S105 def __init__(self, pubnub, channels: Union[str, List[str]] = None, channel_groups: Union[str, List[str]] = None, users: Union[str, List[str]] = None, spaces: Union[str, List[str]] = None, diff --git a/pubnub/endpoints/access/revoke_token.py b/pubnub/endpoints/access/revoke_token.py index 38cede49e..a6940bb7f 100644 --- a/pubnub/endpoints/access/revoke_token.py +++ b/pubnub/endpoints/access/revoke_token.py @@ -12,7 +12,7 @@ class PNRevokeTokenResultEnvelope(Envelope): class RevokeToken(Endpoint): - REVOKE_TOKEN_PATH = "/v3/pam/%s/grant/%s" + REVOKE_TOKEN_PATH = "/v3/pam/%s/grant/%s" # noqa: S105 def __init__(self, pubnub, token: str): Endpoint.__init__(self, pubnub) diff --git a/pubnub/errors.py b/pubnub/errors.py index 6f6c8491c..606e61f86 100644 --- a/pubnub/errors.py +++ b/pubnub/errors.py @@ -15,7 +15,7 @@ PNERR_GROUP_MISSING = "Channel group missing" PNERR_MESSAGE_MISSING = "Message missing" PNERR_SUBSCRIBE_KEY_MISSING = "Subscribe key not configured" -PNERR_SECRET_KEY_MISSING = "Secret key is not configured" +PNERR_SECRET_KEY_MISSING = "Secret key is not configured" # noqa: S105 PNERR_PUBLISH_KEY_MISSING = "Publish key not configured" PNERR_PUBLISH_META_WRONG_TYPE = "Publish meta should be dict" PNERR_DEFERRED_NOT_IMPLEMENTED = "Deferred endpoint call is not implemented by this platform" @@ -32,7 +32,7 @@ PNERR_RESOURCES_MISSING = "Resources missing" PNERR_TTL_MISSING = "TTL missing" PNERR_INVALID_META = "Invalid meta parameter" -PNERR_INVALID_ACCESS_TOKEN = "Invalid access token" +PNERR_INVALID_ACCESS_TOKEN = "Invalid access token" # noqa: S105 PNERR_MESSAGE_ACTION_MISSING = "Message action is missing" PNERR_MESSAGE_ACTION_TYPE_MISSING = "Message action type is missing" PNERR_MESSAGE_ACTION_VALUE_MISSING = "Message action value is missing" diff --git a/pubnub/managers.py b/pubnub/managers.py index 69833669a..3cdf9d1d2 100644 --- a/pubnub/managers.py +++ b/pubnub/managers.py @@ -92,7 +92,7 @@ class LinearDelay: @classmethod def calculate(cls, attempt: int, delay=None): base = delay if delay is not None else cls.INTERVAL - return base + round(random.random(), 3) + return base + round(random.random(), 3) # noqa: S311 retry jitter, not security class ExponentialDelay: @@ -105,7 +105,7 @@ class ExponentialDelay: def calculate(cls, attempt: int, minimum_delay=None, maximum_delay=None) -> float: min_delay = minimum_delay if minimum_delay is not None else cls.MIN_DELAY max_backoff = maximum_delay if maximum_delay is not None else cls.MAX_BACKOFF - return min(max_backoff, min_delay * (2 ** attempt)) + round(random.random(), 3) + return min(max_backoff, min_delay * (2 ** attempt)) + round(random.random(), 3) # noqa: S311 class StateManager: diff --git a/pubnub/pubnub.py b/pubnub/pubnub.py index 495a68724..33dd77fb2 100644 --- a/pubnub/pubnub.py +++ b/pubnub/pubnub.py @@ -513,7 +513,7 @@ def _run(self): return try: self._callback() - except Exception: + except Exception: # noqa: S110 # TODO: handle the exception pass finally: diff --git a/pubnub/request_handlers/httpx.py b/pubnub/request_handlers/httpx.py index 7a1fe8727..21c3dc4c6 100644 --- a/pubnub/request_handlers/httpx.py +++ b/pubnub/request_handlers/httpx.py @@ -111,7 +111,7 @@ def _force_shutdown_connections(session): if sock is None: continue sock.shutdown(socket.SHUT_RDWR) - except (OSError, Exception): + except (OSError, Exception): # noqa: S110 best-effort socket shutdown pass except Exception as e: logger.debug(f"Error iterating connection pool: {e}") diff --git a/requirements-dev.txt b/requirements-dev.txt index 27b01f438..6d601b1e0 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,7 +1,7 @@ pyyaml>=6.0 pytest-cov>=6.0.0 pycryptodomex>=3.21.0 -flake8>=7.1.2 +ruff==0.17.* pytest>=8.3.5 pytest-asyncio>=1.0.0 httpx>=0.28 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 000000000..680260418 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,57 @@ +line-length = 120 +extend-exclude = ["scripts", "src", ".cache", ".idea", ".tox", "venv"] + +[lint] +preview = true +select = ["E", "F", "W", "S", "B", "PL", "SIM", "C90"] +ignore = [ + "E402", # module-level import not at top + "F811", # redefinition of unused name + "S101", # assert + "PLR0904", # too many public methods + "PLR0911", # too many return statements + "PLR0912", # too many branches + "PLR0913", # too many arguments + "PLR0914", # too many local variables + "PLR0915", # too many statements + "PLR0916", # too many boolean expressions + "PLR0917", # too many positional arguments + "PLR2004", # magic value in comparison + "PLR6301", # method could be a function (no self use) + "PLW0717", # too many statements in try clause + "B006", # mutable argument default + "B018", # useless expression + "B028", # warnings.warn without explicit stacklevel + "B903", # class that could be a dataclass/namedtuple + "B904", # raise inside except without `from` + "B909", # mutating a collection while iterating over it + "SIM102", # nested ifs that can be collapsed + "SIM105", # try/except/pass that can use contextlib.suppress + "SIM108", # if/else block that can be a ternary + "SIM113", # manual loop counter instead of enumerate + "SIM114", # if branches with identical bodies + "SIM115", # open() without a context manager + "SIM118", # `key in dict.keys()` + "SIM211", # `False if x else True` instead of `not x` + "SIM300", # Yoda condition + "SIM401", # if/else that can be dict.get + "PLC0414", # useless import alias + "PLC0415", # import outside top level + "PLC1901", # comparison to empty string + "PLE0307", # __str__ returning non-str + "PLR1722", # exit() instead of sys.exit() + "PLR5501", # else + if that can be elif + "PLR6201", # list/tuple literal in membership test (use set) + "PLW0108", # unnecessary lambda + "PLW0127", # self-assigning variable + "PLW0128", # redeclared assigned name + "PLW1508", # non-string default for os.getenv + "PLW1514", # open() without explicit encoding +] + +[lint.mccabe] +max-complexity = 25 + +[lint.per-file-ignores] +"tests/**" = ["S", "B", "PL", "SIM", "C90"] +"examples/**" = ["S104", "S108", "S110"] diff --git a/scripts/run-tests.py b/scripts/run-tests.py index 80ff48a0c..ccd216c22 100755 --- a/scripts/run-tests.py +++ b/scripts/run-tests.py @@ -12,7 +12,7 @@ os.chdir(os.path.join(REPO_ROOT)) tcmn = 'py.test tests --cov=pubnub --ignore=tests/manual/' -fcmn = 'flake8 --exclude=scripts/,src/,.cache,.git,.idea,.tox,._trial_temp/,venv/ --ignore F811,E402' +fcmn = 'ruff check .' def run(command): diff --git a/setup.cfg b/setup.cfg index c43582b64..7a066ed4c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,2 @@ [tool:pytest] norecursedirs = benchmarks - -[flake8] -max-line-length = 120 -ignore=E402 \ No newline at end of file diff --git a/tests/integrational/native_sync/test_publish.py b/tests/integrational/native_sync/test_publish.py index 7a81f2447..d3c70c351 100644 --- a/tests/integrational/native_sync/test_publish.py +++ b/tests/integrational/native_sync/test_publish.py @@ -1,6 +1,5 @@ import logging import unittest -import urllib import urllib.parse import pubnub