diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d73e179..0c077e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,13 @@ name: Python CI on: pull_request: - branches: [master] + branches: [main] push: - branches: [master] + branches: [main] + release: + types: [released] + +permissions: {} jobs: test: @@ -15,12 +19,6 @@ jobs: fail-fast: false matrix: include: - - python-version: "3.9" - platform: ubuntu-latest - toxenv: py39 - - python-version: "3.10" - platform: ubuntu-latest - toxenv: py310 - python-version: "3.11" platform: ubuntu-latest toxenv: py311 @@ -36,12 +34,17 @@ jobs: - python-version: "3.13" platform: windows-latest toxenv: py313 + - python-version: "3.14" + platform: windows-latest + toxenv: py314 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} @@ -50,3 +53,72 @@ jobs: - name: Run lint run: tox -e lint + + - name: Run tests + run: tox -e ${{ matrix.toxenv }} -- -vv + + release: + name: Semantic Release + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + needs: test + runs-on: ubuntu-latest + concurrency: + group: semantic-release-main + permissions: + contents: write + outputs: + released: ${{ steps.release.outputs.released }} + tag: ${{ steps.release.outputs.tag }} + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Run semantic release + id: release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: pipx run --python python 'python-semantic-release==10.7.0' -v version --no-changelog --skip-build + + publish: + name: Build & Publish to PyPI + # The release job is skipped for releases published manually in GitHub. + if: >- + !cancelled() && needs.test.result == 'success' && + (github.event_name == 'release' || + (needs.release.result == 'success' && needs.release.outputs.released == 'true')) + needs: [test, release] + runs-on: ubuntu-latest + permissions: + id-token: write + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event_name == 'release' && github.ref || format('refs/tags/{0}', needs.release.outputs.tag) }} + # setuptools_scm needs tags to derive a release version + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install build + run: python -m pip install --upgrade build + + - name: Build package + run: python -m build + + - name: Upload to PyPI + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + skip-existing: true diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000..ab474f4 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,22 @@ +name: zizmor + +on: + pull_request: + push: + branches: [main] + +permissions: {} + +jobs: + zizmor: + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: zizmorcore/zizmor-action@1b4550e929643b8b26a62303c6bd64814271a4f1 # v0.9.2 + with: + version: v1.33.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a923d1e..5e2e121 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,12 +1,12 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.12.0 + rev: v0.17.6 hooks: - id: ruff-check args: [--fix] - id: ruff-format - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v6.0.0 hooks: - id: check-ast - id: check-docstring-first @@ -22,7 +22,7 @@ repos: args: ['--django'] - id: check-json - repo: https://github.com/codespell-project/codespell - rev: v2.4.1 + rev: v2.4.3 hooks: - id: codespell exclude_types: [json] @@ -43,6 +43,10 @@ repos: language: system require_serial: true types: [python] + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.33.1 + hooks: + - id: zizmor default_language_version: python: python3 diff --git a/README.md b/README.md index a565a02..a4d3472 100644 --- a/README.md +++ b/README.md @@ -1 +1,49 @@ -Common config for Sentry for Fuzzing tools +# mozsec-sentry + +Common config for [Sentry](https://sentry.io/) for Fuzzing tools. + +This package centralises the Sentry setup shared by Mozilla's fuzzing tools, so +each tool gets identical error reporting and the same extra diagnostic context +attached to every event. + +## Install + +```sh +pip install mozsec-sentry +``` + +## Usage + +Call `init()` once, as early as possible in your program's startup: + +```python +from mozsec_sentry import init + +init() +``` + +`init()` is a no-op unless the `SENTRY_DSN` environment variable is set, so it +is safe to call unconditionally — tools can ship the call and only enable +reporting where a DSN is configured. It is also deliberately a no-op while +running under pytest (detected via `PYTEST_CURRENT_TEST`) so test suites never +report to Sentry. + +## Configuration + +| Variable | Purpose | +| --- | --- | +| `SENTRY_DSN` | The Sentry DSN to report to. Reporting is disabled if unset. | +| `TASK_ID` | Taskcluster task ID, used to build a link back to the task. | +| `TASKCLUSTER_ROOT_URL` | Taskcluster deployment root URL. Defaults to `unknown`. | +| `RUN_ID` | Taskcluster run ID. Defaults to `unknown`. | +| `TASKCLUSTER_FUZZING_POOL` | Name of the fuzzing pool the task belongs to. | + +## Event context + +Every event is enriched via a `before_send` hook with: + +- **System Stats** — free memory (MB), free disk (MB), and OS name. +- **Taskcluster** — task ID, a direct task URL, and the fuzzing pool, when the + corresponding environment variables are present. +- An `origin_module` tag naming the module the exception was raised from, which + makes it possible to group issues by the component at fault. diff --git a/pyproject.toml b/pyproject.toml index 858246e..39fd7ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ log_level = "DEBUG" [tool.ruff] fix = true -target-version = "py39" +target-version = "py310" [tool.ruff.lint] select = [ @@ -73,4 +73,10 @@ select = [ "W", ] +[tool.semantic_release] +tag_format = "{version}" + +[tool.semantic_release.branches.main] +match = "^main$" + [tool.setuptools_scm] diff --git a/setup.cfg b/setup.cfg index e1c505c..6fd517b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,32 +1,38 @@ [metadata] classifiers = - Development Status :: 5 - Production/Stable + Development Status :: 4 - Beta Intended Audience :: Developers License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) Programming Language :: Python :: 3 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.11 + Programming Language :: Python :: 3.12 + Programming Language :: Python :: 3.13 Topic :: Security Topic :: Software Development :: Testing description = Common config for Sentry for Fuzzing tools keywords = fuzz fuzzing security test testing license = MPL 2.0 +license_files = LICENSE.md long_description = file: README.md long_description_content_type = text/markdown maintainer = Mozilla Fuzzing Team maintainer_email = fuzzing@mozilla.com -name = sentry-fuzzing-config +name = mozsec-sentry platforms = any url = https://github.com/MozillaSecurity/sentry [options] install_requires = psutil - sentry_sdk + sentry-sdk >= 1.44.0 package_dir = = src packages = - sentry_fuzzing_config + mozsec_sentry zip_safe = False -python_requires = >=3.9 +python_requires = >=3.10 [options.extras_require] dev = @@ -34,5 +40,5 @@ dev = tox [options.package_data] -sentry_fuzzing_config = +mozsec_sentry = py.typed diff --git a/src/sentry_fuzzing_config/__init__.py b/src/mozsec_sentry/__init__.py similarity index 100% rename from src/sentry_fuzzing_config/__init__.py rename to src/mozsec_sentry/__init__.py diff --git a/src/sentry_fuzzing_config/py.typed b/src/mozsec_sentry/py.typed similarity index 100% rename from src/sentry_fuzzing_config/py.typed rename to src/mozsec_sentry/py.typed diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..dd6c1ae --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,145 @@ +"""Tests for mozsec_sentry.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +import pytest + +from mozsec_sentry import _add_system_context, init + +if TYPE_CHECKING: + from pytest_mock import MockerFixture + from sentry_sdk.types import Event, Hint + +TASKCLUSTER_VARS = ( + "RUN_ID", + "SENTRY_DSN", + "TASK_ID", + "TASKCLUSTER_FUZZING_POOL", + "TASKCLUSTER_ROOT_URL", +) + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Remove any ambient config so tests do not inherit the host environment.""" + for var in TASKCLUSTER_VARS: + monkeypatch.delenv(var, raising=False) + + +def _event() -> Event: + """Build an empty event to pass through the before_send hook.""" + return cast("Event", {}) + + +def _hint(**kwargs: object) -> Hint: + """Build a hint dict to pass through the before_send hook.""" + return cast("Hint", dict(kwargs)) + + +def _traceback_hint() -> Hint: + """Build a hint carrying a real traceback raised from this module.""" + with pytest.raises(RuntimeError) as excinfo: + raise RuntimeError("boom") + return _hint(exc_info=(excinfo.type, excinfo.value, excinfo.tb)) + + +def test_system_stats_added() -> None: + """System Stats context is always populated.""" + result = _add_system_context(_event(), _hint()) + stats = result["contexts"]["System Stats"] + assert set(stats) == {"Memory free (MB)", "Disk free (MB)", "OS"} + assert isinstance(stats["Memory free (MB)"], int) + assert isinstance(stats["Disk free (MB)"], int) + assert stats["OS"] + + +def test_taskcluster_empty_without_env() -> None: + """Taskcluster context exists but stays empty when no task vars are set.""" + result = _add_system_context(_event(), _hint()) + assert result["contexts"]["Taskcluster"] == {} + + +def test_taskcluster_context(monkeypatch: pytest.MonkeyPatch) -> None: + """Task ID and a browsable task URL are recorded.""" + monkeypatch.setenv("TASK_ID", "abc123") + monkeypatch.setenv("TASKCLUSTER_ROOT_URL", "https://tc.example.com") + monkeypatch.setenv("RUN_ID", "2") + result = _add_system_context(_event(), _hint()) + assert result["contexts"]["Taskcluster"] == { + "Task ID": "abc123", + "Task URL": "https://tc.example.com/tasks/abc123/runs/2", + } + + +def test_taskcluster_context_defaults(monkeypatch: pytest.MonkeyPatch) -> None: + """Root URL and run ID fall back to 'unknown' when unset.""" + monkeypatch.setenv("TASK_ID", "abc123") + result = _add_system_context(_event(), _hint()) + assert ( + result["contexts"]["Taskcluster"]["Task URL"] + == "unknown/tasks/abc123/runs/unknown" + ) + + +def test_fuzzing_pool(monkeypatch: pytest.MonkeyPatch) -> None: + """The fuzzing pool is recorded independently of the task ID.""" + monkeypatch.setenv("TASKCLUSTER_FUZZING_POOL", "pool-42") + result = _add_system_context(_event(), _hint()) + assert result["contexts"]["Taskcluster"] == {"Fuzzing Pool": "pool-42"} + + +def test_origin_module_tag() -> None: + """The module raising the exception is tagged for issue grouping.""" + result = _add_system_context(_event(), _traceback_hint()) + assert result["tags"]["origin_module"] == __name__ + + +def test_origin_module_tag_preserves_existing() -> None: + """An existing tags dict is extended, not replaced.""" + event = cast("Event", {"tags": {"keep": "me"}}) + result = _add_system_context(event, _traceback_hint()) + assert result["tags"]["keep"] == "me" + assert result["tags"]["origin_module"] == __name__ + + +@pytest.mark.parametrize( + "hint_kwargs", + [{}, {"exc_info": None}], + ids=["no-exc-info", "null-exc-info"], +) +def test_no_origin_module_without_traceback(hint_kwargs: dict[str, object]) -> None: + """Events without exception info are left untagged rather than raising.""" + result = _add_system_context(_event(), _hint(**hint_kwargs)) + assert "tags" not in result + + +def test_init_without_dsn(mocker: MockerFixture) -> None: + """init() is a no-op when SENTRY_DSN is unset.""" + sentry_init = mocker.patch("mozsec_sentry.sentry_init") + init() + assert not sentry_init.called + + +def test_init_skipped_under_pytest( + monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture +) -> None: + """init() refuses to report while running under pytest.""" + monkeypatch.setenv("SENTRY_DSN", "https://key@example.com/1") + monkeypatch.setenv("PYTEST_CURRENT_TEST", "test") + sentry_init = mocker.patch("mozsec_sentry.sentry_init") + init() + assert not sentry_init.called + + +def test_init_enabled(monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture) -> None: + """init() configures the SDK with the DSN and the context hook.""" + monkeypatch.setenv("SENTRY_DSN", "https://key@example.com/1") + monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False) + sentry_init = mocker.patch("mozsec_sentry.sentry_init") + init() + sentry_init.assert_called_once_with( + dsn="https://key@example.com/1", + before_send=_add_system_context, + ) diff --git a/tox.ini b/tox.ini index 580d227..5f2bae7 100644 --- a/tox.ini +++ b/tox.ini @@ -43,6 +43,8 @@ commands = mypy --install-types --non-interactive {posargs} deps = mypy==v1.16.0 + pytest + pytest-mock usedevelop = true [testenv:pylint] @@ -50,6 +52,8 @@ commands = pylint {posargs} deps = pylint==3.3.7 + pytest + pytest-mock usedevelop = true [testenv:pypi]