juniper-observability 0.4.2__tar.gz → 0.4.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/PKG-INFO +15 -7
  2. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/README.md +12 -4
  3. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/_version.py +1 -1
  4. juniper_observability-0.4.3/juniper_observability/sentry.py +517 -0
  5. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability.egg-info/PKG-INFO +15 -7
  6. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability.egg-info/requires.txt +2 -2
  7. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/pyproject.toml +7 -3
  8. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_public_api.py +11 -2
  9. juniper_observability-0.4.3/tests/test_sentry.py +1592 -0
  10. juniper_observability-0.4.2/juniper_observability/sentry.py +0 -195
  11. juniper_observability-0.4.2/tests/test_sentry.py +0 -628
  12. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/__init__.py +0 -0
  13. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/constants.py +0 -0
  14. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/health/__init__.py +0 -0
  15. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/health/models.py +0 -0
  16. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/health/probe.py +0 -0
  17. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/logging.py +0 -0
  18. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/middleware/__init__.py +0 -0
  19. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/middleware/metrics_auth.py +0 -0
  20. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/middleware/prometheus.py +0 -0
  21. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/middleware/request_id.py +0 -0
  22. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/prometheus.py +0 -0
  23. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/prometheus_helpers.py +0 -0
  24. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/py.typed +0 -0
  25. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability/testing.py +0 -0
  26. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability.egg-info/SOURCES.txt +0 -0
  27. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability.egg-info/dependency_links.txt +0 -0
  28. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/juniper_observability.egg-info/top_level.txt +0 -0
  29. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/setup.cfg +0 -0
  30. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_health_models.py +0 -0
  31. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_health_probe.py +0 -0
  32. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_logging.py +0 -0
  33. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_metrics_auth_middleware.py +0 -0
  34. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_prometheus_helpers.py +0 -0
  35. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_prometheus_middleware.py +0 -0
  36. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_prometheus_utils.py +0 -0
  37. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_request_id_middleware.py +0 -0
  38. {juniper_observability-0.4.2 → juniper_observability-0.4.3}/tests/test_testing_fixture.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: juniper-observability
3
- Version: 0.4.2
3
+ Version: 0.4.3
4
4
  Summary: Shared observability primitives (health models, logging, middleware, Sentry, Prometheus) for the Juniper ML platform
5
5
  Author: Paul Calnon
6
6
  License: MIT
@@ -24,7 +24,7 @@ Requires-Dist: starlette>=0.27
24
24
  Provides-Extra: prometheus
25
25
  Requires-Dist: prometheus-client>=0.20.0; extra == "prometheus"
26
26
  Provides-Extra: sentry
27
- Requires-Dist: sentry-sdk[fastapi]>=2.35.0; extra == "sentry"
27
+ Requires-Dist: sentry-sdk[fastapi]<4,>=2.35.0; extra == "sentry"
28
28
  Provides-Extra: all
29
29
  Requires-Dist: juniper-observability[prometheus,sentry]; extra == "all"
30
30
  Provides-Extra: test
@@ -34,7 +34,7 @@ Requires-Dist: pytest-cov>=5.0; extra == "test"
34
34
  Requires-Dist: httpx>=0.27; extra == "test"
35
35
  Requires-Dist: fastapi>=0.110; extra == "test"
36
36
  Requires-Dist: prometheus-client>=0.20.0; extra == "test"
37
- Requires-Dist: sentry-sdk[fastapi]>=2.35.0; extra == "test"
37
+ Requires-Dist: sentry-sdk[fastapi]<4,>=2.35.0; extra == "test"
38
38
 
39
39
  # juniper-observability
40
40
 
@@ -99,10 +99,16 @@ from juniper_observability.testing import reset_prometheus_registry # pytest fi
99
99
  | `RequestIdMiddleware`, `PrometheusMiddleware` | Starlette middlewares applied across the service fleet. |
100
100
  | Health-response models | Pydantic models for the `/v1/health/ready` endpoint. |
101
101
  | Structured-JSON logging | Logging configuration with `request_id` propagation. |
102
- | Sentry init | `configure_sentry` passes `include_local_variables=False` (no switch to turn locals back on) and the SEC-10 `before_send` hook always runs. The hook also deletes frame `vars`. |
102
+ | Sentry init | `configure_sentry` works with sentry-sdk 2.x and 3.x. It never captures frame locals (2.x: `include_local_variables=False`; 3.x: `data_collection` with `stack_frame_variables` off; no switch to turn them back on), and the SEC-10 `before_send` hook always runs. The hook also deletes frame `vars`. On 3.x a second hook, `before_send_span`, scrubs the same headers from span attributes. |
103
103
 
104
104
  `configure_sentry` never captures frame locals. Sentry's `EventScrubber` redacts locals by name, and the local that held the configured API key during the comparison in the juniper-canopy#683 finding is not on that list. The `before_send` hook deletes `vars` as well, because the opt-in `PureEvalIntegration` (sentry-sdk 2.58.0) writes them without consulting `include_local_variables`. Releases up to and including **0.4.0** use the SDK default (`True`). There is no parameter to turn locals back on.
105
105
 
106
+ On sentry-sdk 3.x, which removed `send_default_pii`, `include_local_variables`, `enable_logs` and `before_send_transaction`, the same choices go through `data_collection`.
107
+ It also turns off what 2.x did not collect under the same `send_pii` (SQL parameters, redis arguments, queue job arguments, GenAI, MCP and GraphQL data), and it sends no request bodies.
108
+ 3.0.0 deleted 2.x's `EventScrubber`, so on 3.x the hooks redact its denylisted names (`password`, `api_key`, `token` ...) themselves, and without `send_pii` its PII names too (`ip_address`, `remote_addr`, `x_forwarded_for`, `x_real_ip`). On 2.x they leave that to the SDK, so 2.x output is unchanged.
109
+ Spans replace transactions there, and carry each request header as an attribute, which `before_send_span` scrubs.
110
+ 3.x installs no logging integration by default, so `configure_sentry` passes one with `event_level=logging.ERROR`, and an ERROR record is still an error event.
111
+
106
112
  Operator notes: [juniper-ml REFERENCE](../docs/REFERENCE.md#non-ascii-api-keys-and-sentry-frame-locals).
107
113
 
108
114
  **Per-service metrics stay in each repo.** This package exposes only *cross-cutting* infrastructure;
@@ -123,9 +129,11 @@ and collector helpers (pin `>=0.2.0`). The client libraries
123
129
 
124
130
  **Live** on PyPI, published independently of the meta-package on `juniper-observability-v*` tags. The
125
131
  current version is shown by the badge above; see [`CHANGELOG.md`](./CHANGELOG.md). Consumers should
126
- pin `juniper-observability>=0.4.2`, the security patch in which `configure_sentry` also scrubs
127
- Sentry transactions, parsed cookies and four more credential headers; 0.4.1 stopped it sending
128
- frame-local variables.
132
+ pin `juniper-observability>=0.4.3`, the first release whose `configure_sentry` runs on sentry-sdk 3.x:
133
+ 0.4.2's `sentry` extra admits 3.x, and on 3.x its `configure_sentry` raises `TypeError` at startup
134
+ whenever a DSN is set. 0.4.2 was the security patch in which `configure_sentry` also scrubs Sentry
135
+ transactions, parsed cookies and four more credential headers; 0.4.1 stopped it sending frame-local
136
+ variables.
129
137
 
130
138
  ### Compatibility policy — pinning, not deprecation cycles
131
139
 
@@ -61,10 +61,16 @@ from juniper_observability.testing import reset_prometheus_registry # pytest fi
61
61
  | `RequestIdMiddleware`, `PrometheusMiddleware` | Starlette middlewares applied across the service fleet. |
62
62
  | Health-response models | Pydantic models for the `/v1/health/ready` endpoint. |
63
63
  | Structured-JSON logging | Logging configuration with `request_id` propagation. |
64
- | Sentry init | `configure_sentry` passes `include_local_variables=False` (no switch to turn locals back on) and the SEC-10 `before_send` hook always runs. The hook also deletes frame `vars`. |
64
+ | Sentry init | `configure_sentry` works with sentry-sdk 2.x and 3.x. It never captures frame locals (2.x: `include_local_variables=False`; 3.x: `data_collection` with `stack_frame_variables` off; no switch to turn them back on), and the SEC-10 `before_send` hook always runs. The hook also deletes frame `vars`. On 3.x a second hook, `before_send_span`, scrubs the same headers from span attributes. |
65
65
 
66
66
  `configure_sentry` never captures frame locals. Sentry's `EventScrubber` redacts locals by name, and the local that held the configured API key during the comparison in the juniper-canopy#683 finding is not on that list. The `before_send` hook deletes `vars` as well, because the opt-in `PureEvalIntegration` (sentry-sdk 2.58.0) writes them without consulting `include_local_variables`. Releases up to and including **0.4.0** use the SDK default (`True`). There is no parameter to turn locals back on.
67
67
 
68
+ On sentry-sdk 3.x, which removed `send_default_pii`, `include_local_variables`, `enable_logs` and `before_send_transaction`, the same choices go through `data_collection`.
69
+ It also turns off what 2.x did not collect under the same `send_pii` (SQL parameters, redis arguments, queue job arguments, GenAI, MCP and GraphQL data), and it sends no request bodies.
70
+ 3.0.0 deleted 2.x's `EventScrubber`, so on 3.x the hooks redact its denylisted names (`password`, `api_key`, `token` ...) themselves, and without `send_pii` its PII names too (`ip_address`, `remote_addr`, `x_forwarded_for`, `x_real_ip`). On 2.x they leave that to the SDK, so 2.x output is unchanged.
71
+ Spans replace transactions there, and carry each request header as an attribute, which `before_send_span` scrubs.
72
+ 3.x installs no logging integration by default, so `configure_sentry` passes one with `event_level=logging.ERROR`, and an ERROR record is still an error event.
73
+
68
74
  Operator notes: [juniper-ml REFERENCE](../docs/REFERENCE.md#non-ascii-api-keys-and-sentry-frame-locals).
69
75
 
70
76
  **Per-service metrics stay in each repo.** This package exposes only *cross-cutting* infrastructure;
@@ -85,9 +91,11 @@ and collector helpers (pin `>=0.2.0`). The client libraries
85
91
 
86
92
  **Live** on PyPI, published independently of the meta-package on `juniper-observability-v*` tags. The
87
93
  current version is shown by the badge above; see [`CHANGELOG.md`](./CHANGELOG.md). Consumers should
88
- pin `juniper-observability>=0.4.2`, the security patch in which `configure_sentry` also scrubs
89
- Sentry transactions, parsed cookies and four more credential headers; 0.4.1 stopped it sending
90
- frame-local variables.
94
+ pin `juniper-observability>=0.4.3`, the first release whose `configure_sentry` runs on sentry-sdk 3.x:
95
+ 0.4.2's `sentry` extra admits 3.x, and on 3.x its `configure_sentry` raises `TypeError` at startup
96
+ whenever a DSN is set. 0.4.2 was the security patch in which `configure_sentry` also scrubs Sentry
97
+ transactions, parsed cookies and four more credential headers; 0.4.1 stopped it sending frame-local
98
+ variables.
91
99
 
92
100
  ### Compatibility policy — pinning, not deprecation cycles
93
101
 
@@ -1,3 +1,3 @@
1
1
  """Single source of truth for the package version."""
2
2
 
3
- __version__ = "0.4.2"
3
+ __version__ = "0.4.3"
@@ -0,0 +1,517 @@
1
+ """Sentry initialization with reconciled signature and SEC-10 hook.
2
+
3
+ This module exposes the **superset** signature originally introduced
4
+ in juniper-data for SEC-10 (security review of Sentry forwarding) and
5
+ makes it the cross-service standard:
6
+
7
+ - ``send_pii`` is keyword-only, defaulting to ``False``.
8
+ - Frame-local variables are never captured (``include_local_variables=False``).
9
+ The SDK default is ``True``, which snapshots every frame's locals into
10
+ each error event. An exception raised inside an API-key comparison
11
+ therefore shipped the comparison loop's local holding the REAL
12
+ configured key -- found by the validation of juniper-canopy#683
13
+ (2026-09-24), where an anonymous ``X-API-Key: \\xa0`` made
14
+ ``hmac.compare_digest`` raise ``TypeError``. The SDK's own
15
+ ``EventScrubber`` did not help: it redacts locals by NAME. ``api_key``,
16
+ the PRESENTED key, is on its default denylist; ``candidate``, the loop
17
+ variable holding the CONFIGURED key, is not. No name list can be
18
+ complete, so the fix is to capture no locals at all.
19
+ - A ``before_send`` hook always scrubs the request headers named in
20
+ ``_SENTRY_SENSITIVE_HEADERS`` (``X-API-Key``, ``Authorization`` and
21
+ ``Cookie``; from 0.4.2 also ``Proxy-Authorization``,
22
+ ``Sec-WebSocket-Protocol``, ``X-CSRF-Token`` and ``X-XSRF-Token``) from
23
+ outbound events regardless of ``send_default_pii``, and deletes any
24
+ frame ``vars`` that still reach
25
+ it — defense in depth so that future Sentry SDK changes (replay,
26
+ custom integrations) cannot leak credentials. That second half is not
27
+ hypothetical: the opt-in ``PureEvalIntegration`` writes frame ``vars``
28
+ from its own event processor without consulting
29
+ ``include_local_variables`` (``sentry_sdk/integrations/pure_eval.py``,
30
+ sentry-sdk 2.58.0), and event processors run before ``before_send``.
31
+ - The same hook is installed as ``before_send_transaction``, because the
32
+ SDK never hands a transaction to ``before_send``. Under
33
+ ``send_default_pii=True`` the SDK's own header filter is off, and its
34
+ ``EventScrubber`` denylist names ``x_api_key`` but not ``x-api-key``, so
35
+ until 0.4.2 every sampled transaction carried the raw ``X-API-Key``
36
+ (round-42 finding F2, 2026-09-24).
37
+ - The hook also redacts the request's parsed ``cookies``, which the
38
+ Starlette and FastAPI integrations add under ``send_default_pii=True``
39
+ beside the ``Cookie`` header itself. The SDK's denylist redacts a cookie
40
+ by NAME (``session``, ``csrftoken`` ...), so any other name reached the
41
+ wire, in error events and transactions alike, until 0.4.2. A dict keeps
42
+ its names and loses every value; a non-empty ``cookies`` of any other
43
+ shape is dropped.
44
+ - Still OUTSIDE the hook (left for R-OBS-SC-3, to be designed and validated
45
+ on its own): query strings,
46
+ Sentry Logs (``enable_logs=True`` has no ``before_send_log``), request
47
+ bodies, breadcrumbs, exception values and list-shaped ``headers``. On 3.x
48
+ the hooks do only what 2.x's deleted ``EventScrubber`` did to bodies and
49
+ breadcrumb data: replace values under the names it denylisted.
50
+
51
+ Both sentry-sdk majors are supported, and the installed one's major decides
52
+ which options are passed (:func:`_sentry_sdk_major`):
53
+
54
+ - On 2.x the options are the ones 0.4.2 passed: ``send_default_pii``,
55
+ ``include_local_variables=False``, ``enable_logs=True``, and the hook as
56
+ ``before_send`` and ``before_send_transaction``.
57
+ - sentry-sdk 3.0.0 removed every one of those but ``before_send``, and
58
+ ``sentry_sdk.init`` raises ``TypeError`` for an unknown option. On 3.x the
59
+ same choices go through ``data_collection`` (:func:`_data_collection`).
60
+ - 3.x streams spans in place of transactions. The server span carries each
61
+ request header as an ``http.request.header.<name>`` attribute, so
62
+ :func:`_strip_sensitive_span_attributes` is installed as
63
+ ``before_send_span``. The SDK's own denylist matches no term in
64
+ ``sec-websocket-protocol``: with the SDK's defaults juniper-canopy's
65
+ WebSocket key reached every span raw (measured on 3.0.0).
66
+ - 3.x no longer installs the logging integration by default. It is passed
67
+ with ``event_level=logging.ERROR``, so an ERROR record is still an error
68
+ event and INFO and above still become Sentry Logs and breadcrumbs, as on 2.x
69
+ with ``enable_logs=True``.
70
+
71
+ ``configure_sentry`` is a no-op when ``dsn`` is ``None`` or the empty
72
+ string, so consumers can call it unconditionally during startup.
73
+ """
74
+
75
+ import logging as _logging
76
+
77
+ DEFAULT_SENTRY_TRACES_SAMPLE_RATE = 0.1
78
+
79
+ # SEC-10: header names that may carry API keys, credentials or session identifiers, compared
80
+ # lower-case. 0.4.2 added the last four. ``sec-websocket-protocol`` is where juniper-canopy's
81
+ # server reads a WebSocket key (``bearer, <key>``) when its opt-in ``ws_auth_enabled`` is on;
82
+ # it and the two CSRF tokens are on neither of the SDK's own lists, so they reached Sentry even
83
+ # under the default ``send_pii=False``. sentry-sdk 2.35.0 filters ``proxy-authorization`` in
84
+ # neither mode (2.73.0 does, in both).
85
+ _SENTRY_SENSITIVE_HEADERS = frozenset(
86
+ {
87
+ "x-api-key",
88
+ "authorization",
89
+ "cookie",
90
+ "proxy-authorization",
91
+ "sec-websocket-protocol",
92
+ "x-csrf-token",
93
+ "x-xsrf-token",
94
+ }
95
+ )
96
+
97
+ # Headers that carry the client's address, compared lower-case. sentry-sdk 2.x removes both from every
98
+ # event unless ``send_default_pii`` is on (``SENSITIVE_ENV_KEYS`` in ``integrations/_wsgi_common.py``,
99
+ # 2.35.0 and 2.76.0). 3.x's denylist matches neither, so ``_data_collection`` adds them to it when
100
+ # ``send_pii`` is off.
101
+ _SENTRY_ADDRESS_HEADERS = frozenset({"x-forwarded-for", "x-real-ip"})
102
+
103
+ # sentry-sdk 3.x records each request header on the server span under this prefix, as a one-item list.
104
+ _SPAN_REQUEST_HEADER_PREFIX = "http.request.header."
105
+
106
+ # sentry-sdk 2.x's ``EventScrubber`` security denylist (``DEFAULT_DENYLIST`` in ``scrubber.py``, 2.76.0),
107
+ # normalised as 2.76.0 normalises it: lower-case, ``-`` to ``_``. By default 2.x replaces the value of
108
+ # every such top-level KEY in request headers and cookies, ``request.data``, ``extra``, ``user``, each
109
+ # breadcrumb's ``data``, frame ``vars`` and each span's ``data``. sentry-sdk 3.0.0 deleted the scrubber and
110
+ # put nothing in its place for most of those containers, so on 3.x the hooks apply the list themselves
111
+ # (:func:`_redact_by_name`). On 2.x they leave it to the SDK: 2.35.0 matches names without reading ``-``
112
+ # as ``_``, so a second pass would change what 2.x sends.
113
+ _SENTRY_DENYLIST = frozenset(
114
+ name.lower().replace("-", "_")
115
+ for name in (
116
+ "password",
117
+ "passwd",
118
+ "secret",
119
+ "api_key",
120
+ "apikey",
121
+ "auth",
122
+ "credentials",
123
+ "mysql_pwd",
124
+ "privatekey",
125
+ "private_key",
126
+ "token",
127
+ "session",
128
+ "csrftoken",
129
+ "sessionid",
130
+ "x_csrftoken",
131
+ "set_cookie",
132
+ "cookie",
133
+ "authorization",
134
+ "proxy-authorization",
135
+ "x_api_key",
136
+ "aiohttp_session",
137
+ "connect.sid",
138
+ "csrf_token",
139
+ "csrf",
140
+ "_csrf",
141
+ "_csrf_token",
142
+ "PHPSESSID",
143
+ "_session",
144
+ "symfony",
145
+ "user_session",
146
+ "_xsrf",
147
+ "XSRF-TOKEN",
148
+ )
149
+ )
150
+
151
+ # sentry-sdk 2.x's ``EventScrubber`` PII denylist (``DEFAULT_PII_DENYLIST`` in ``scrubber.py``, 2.35.0 and
152
+ # 2.76.0), normalised the same way. Without ``send_default_pii`` 2.x adds it to the list above, so a value
153
+ # under ``ip_address``, ``remote_addr``, ``x_forwarded_for`` or ``x_real_ip`` (in any case, ``-`` or ``_``)
154
+ # is replaced in every container the scrubber reads, request headers included. On 3.x the hooks add it
155
+ # unless PII is on.
156
+ _SENTRY_PII_DENYLIST = frozenset({"x_forwarded_for", "x_real_ip", "ip_address", "remote_addr"})
157
+
158
+ # The ``send_pii`` of the latest ``configure_sentry`` call that initialised a client, and that client.
159
+ # Without ``send_default_pii`` 2.x's ``EventScrubber`` drops ``user.ip_address`` from every event; 3.0.0
160
+ # applies the scope's user to every event whatever ``user_info`` says (``Scope._apply_user_to_event``), so
161
+ # the event hook drops it. False until configured, so a consumer that installs the hook on its own gets
162
+ # 2.x's default. The hooks treat PII as on only for the client ``configure_sentry`` made, while this AND
163
+ # its ``user_info`` say so (:func:`_pii_on`): a later ``sentry_sdk.init`` must not inherit an earlier
164
+ # ``send_pii=True``, whether it turns PII off or leaves ``user_info`` at 3.x's default, True.
165
+ _send_pii = False
166
+ _configured_client = None
167
+
168
+ # Event interfaces whose ``values`` entries each carry their own ``stacktrace``
169
+ # (an event may also carry one top-level ``stacktrace``, e.g. a message
170
+ # captured with ``attach_stacktrace``).
171
+ _SENTRY_STACKTRACE_INTERFACES = ("exception", "threads")
172
+
173
+
174
+ def _strip_frame_local_variables(event):
175
+ """Delete ``vars`` from every stack frame of a Sentry event, in place.
176
+
177
+ Covers every place the Sentry protocol puts frames: each
178
+ ``exception.values[*].stacktrace`` (one per exception in a chain), each
179
+ ``threads.values[*].stacktrace``, and the top-level ``stacktrace``.
180
+ Anything that is not the expected dict/list shape is skipped rather than
181
+ raised on -- a ``before_send`` hook that raises drops the event, and an
182
+ unreadable event is no reason to lose the report.
183
+ """
184
+ stacktraces = [event.get("stacktrace")]
185
+ for interface in _SENTRY_STACKTRACE_INTERFACES:
186
+ container = event.get(interface)
187
+ values = container.get("values") if isinstance(container, dict) else None
188
+ if isinstance(values, list):
189
+ stacktraces.extend(value.get("stacktrace") for value in values if isinstance(value, dict))
190
+ for stacktrace in stacktraces:
191
+ frames = stacktrace.get("frames") if isinstance(stacktrace, dict) else None
192
+ if isinstance(frames, list):
193
+ for frame in frames:
194
+ if isinstance(frame, dict):
195
+ frame.pop("vars", None)
196
+
197
+
198
+ def _redact_denylisted_keys(mapping, names=_SENTRY_DENYLIST):
199
+ """Replace, in place, the value of every top-level key of ``mapping`` that ``names`` holds.
200
+
201
+ The match is 2.76.0's: the whole key, lower-cased, ``-`` read as ``_``. Anything that is not a dict
202
+ is left alone, as 2.x's ``EventScrubber.scrub_dict`` leaves it.
203
+ """
204
+ if isinstance(mapping, dict):
205
+ for key in list(mapping):
206
+ if isinstance(key, str) and key.lower().replace("-", "_") in names:
207
+ mapping[key] = "[Filtered]"
208
+
209
+
210
+ def _sdk_scrubs_by_name() -> bool:
211
+ """True on sentry-sdk 2.x, whose own ``EventScrubber`` has applied both denylists before the hooks run.
212
+
213
+ The hooks then leave every container that scrubber reads as 2.x left it. Redacting again is not a
214
+ no-op on every 2.x: 2.35.0 matches names without reading ``-`` as ``_``, does not read list-shaped
215
+ bodies, and replaces ``user.ip_address`` rather than dropping it. Any error reads as "not 2.x": a
216
+ hook must not raise, and redacting is the safe side.
217
+ """
218
+ try:
219
+ return _sentry_sdk_major() == 2
220
+ except Exception: # noqa: BLE001 — a Sentry hook must never raise
221
+ return False
222
+
223
+
224
+ def _pii_on() -> bool:
225
+ """Whether the hooks may let PII through: the active client is the one ``configure_sentry(send_pii=True)`` made, and its ``user_info`` is on.
226
+
227
+ The module flag alone goes stale: after ``configure_sentry(send_pii=True)``, a consumer's own
228
+ ``sentry_sdk.init`` kept it, and 3.0.0 sent the scope user's address, whether that init turned
229
+ ``user_info`` off or left it at 3.x's default (True), where 2.x's ``send_default_pii`` defaults to
230
+ False. Any other client, no active client, or any error, reads as "no".
231
+ """
232
+ if not _send_pii or _configured_client is None:
233
+ return False
234
+ try:
235
+ import sentry_sdk
236
+
237
+ client = sentry_sdk.get_client()
238
+ if client is not _configured_client:
239
+ return False
240
+ data_collection = client.options.get("data_collection") if client.is_active() else None
241
+ return isinstance(data_collection, dict) and bool(data_collection.get("user_info"))
242
+ except Exception: # noqa: BLE001 — a Sentry hook must never raise
243
+ return False
244
+
245
+
246
+ def _denylist():
247
+ """The names the hooks redact on 3.x: 2.x's security denylist, and without PII its PII denylist too."""
248
+ return _SENTRY_DENYLIST if _pii_on() else _SENTRY_DENYLIST | _SENTRY_PII_DENYLIST
249
+
250
+
251
+ def _redact_by_name(event):
252
+ """What 2.x's ``EventScrubber`` did to an event by default and 3.0.0 no longer does, in the same containers.
253
+
254
+ Request headers and ``request.data`` (a dict, or a list of them), ``extra``, ``user`` and each
255
+ breadcrumb's ``data``: every value under a name in :func:`_denylist`. Without PII,
256
+ ``user.ip_address`` is dropped, as 2.76.0 drops it.
257
+ """
258
+ names = _denylist()
259
+ request_data = event.get("request")
260
+ if isinstance(request_data, dict):
261
+ _redact_denylisted_keys(request_data.get("headers"), names)
262
+ data = request_data.get("data")
263
+ for mapping in data if isinstance(data, list) else [data]:
264
+ _redact_denylisted_keys(mapping, names)
265
+ _redact_denylisted_keys(event.get("extra"), names)
266
+ user = event.get("user")
267
+ if isinstance(user, dict) and not _pii_on():
268
+ user.pop("ip_address", None)
269
+ _redact_denylisted_keys(user, names)
270
+ breadcrumbs = event.get("breadcrumbs")
271
+ crumbs = breadcrumbs.get("values") if isinstance(breadcrumbs, dict) else None
272
+ if isinstance(crumbs, list):
273
+ for crumb in crumbs:
274
+ if isinstance(crumb, dict):
275
+ _redact_denylisted_keys(crumb.get("data"), names)
276
+
277
+
278
+ def _strip_sensitive_headers(event, hint): # noqa: ARG001 — Sentry hook signature
279
+ """Redact sensitive request headers and cookies, and drop frame-local variables.
280
+
281
+ Sentry calls this via ``before_send`` for every error event and via
282
+ ``before_send_transaction`` for every transaction; a transaction never
283
+ reaches ``before_send``. The header filter only rewrites keys in
284
+ :data:`_SENTRY_SENSITIVE_HEADERS` so non-sensitive diagnostic headers
285
+ (user-agent, trace IDs, etc.) still reach Sentry unchanged. Every value
286
+ of a non-empty ``request.cookies`` dict is replaced and its names are
287
+ kept: it is the ``Cookie`` header parsed into names and values, and no
288
+ list of cookie names can say which of them carries a session. A
289
+ non-empty ``cookies`` of any other shape (the protocol also allows a raw
290
+ header string or a list of pairs) is dropped rather than rewritten: the
291
+ SDK's integrations produce the dict, a string would have to be parsed,
292
+ and the protocol reads a string as a raw ``Cookie`` header, which a bare
293
+ ``[Filtered]`` is not.
294
+
295
+ On sentry-sdk 3.x (any SDK but 2.x) it also does what 2.x's ``EventScrubber`` did by default and
296
+ 3.0.0 deleted (:func:`_redact_by_name`): the value of every key 2.x denylists, in request headers,
297
+ ``request.data``, ``extra``, ``user`` and each breadcrumb's ``data``. On 2.x the SDK has done that
298
+ already, and the hook leaves those containers exactly as the SDK left them.
299
+
300
+ It also deletes every frame's ``vars`` (:func:`_strip_frame_local_variables`).
301
+ ``configure_sentry`` already passes ``include_local_variables=False``, so
302
+ the SDK's own capture paths attach none; this is the backstop for
303
+ anything that adds them regardless. The name is kept although the hook
304
+ now does more than headers, because juniper-data and juniper-cascor import
305
+ it by this name (cascor's ``main.py`` passes it to its own
306
+ ``sentry_sdk.init``), and a rename would break those imports.
307
+ """
308
+ if not isinstance(event, dict):
309
+ return event
310
+ request_data = event.get("request", {})
311
+ headers = request_data.get("headers", {}) if isinstance(request_data, dict) else {}
312
+ if isinstance(headers, dict):
313
+ for key in list(headers.keys()):
314
+ if key.lower() in _SENTRY_SENSITIVE_HEADERS:
315
+ headers[key] = "[Filtered]"
316
+ if isinstance(request_data, dict):
317
+ cookies = request_data.get("cookies")
318
+ if isinstance(cookies, dict):
319
+ if cookies:
320
+ request_data["cookies"] = dict.fromkeys(cookies, "[Filtered]")
321
+ elif cookies:
322
+ del request_data["cookies"]
323
+ # 2.x's EventScrubber did this by default; 3.0.0 deleted it. On 2.x, the SDK's own pass stands.
324
+ if not _sdk_scrubs_by_name():
325
+ _redact_by_name(event)
326
+ _strip_frame_local_variables(event)
327
+ return event
328
+
329
+
330
+ def _strip_sensitive_span_attributes(span, hint): # noqa: ARG001 — Sentry hook signature
331
+ """Redact the sensitive request headers a sentry-sdk 3.x span carries as attributes.
332
+
333
+ 3.x streams spans, and hands each one, serialised, to ``before_send_span``: there is no
334
+ transaction any more, so ``before_send_transaction`` no longer exists. The server span records
335
+ each request header as ``http.request.header.<name>``, after the SDK's own header filter, which
336
+ :func:`_data_collection` extends with every name in :data:`_SENTRY_SENSITIVE_HEADERS`. This is
337
+ the backstop, as :func:`_strip_sensitive_headers` is for events: each such attribute whose
338
+ header is in that set, or whose normalised name 2.x denylisted (:func:`_denylist`), becomes
339
+ ``["[Filtered]"]``. Every other attribute under a name 2.x denylisted becomes ``"[Filtered]"``,
340
+ as 2.x's ``EventScrubber`` redacted it in a span's ``data``; the rest are left alone.
341
+
342
+ It never raises, and it returns the span it was given. On 3.0.0 a ``before_send_span`` that
343
+ raises, or that returns anything without a ``name``, makes the SDK send the ORIGINAL span
344
+ (``Client._capture_telemetry``), so a scrubber that failed would fail open.
345
+ """
346
+ attributes = span.get("attributes") if isinstance(span, dict) else None
347
+ if isinstance(attributes, dict):
348
+ names = _denylist()
349
+ for key in list(attributes):
350
+ if not isinstance(key, str):
351
+ continue
352
+ if key.lower().startswith(_SPAN_REQUEST_HEADER_PREFIX):
353
+ header = key[len(_SPAN_REQUEST_HEADER_PREFIX) :].lower()
354
+ if header in _SENTRY_SENSITIVE_HEADERS or header.replace("-", "_") in names:
355
+ attributes[key] = ["[Filtered]"]
356
+ elif key.lower().replace("-", "_") in names:
357
+ # 2.x's EventScrubber redacted these names in every span's ``data``.
358
+ attributes[key] = "[Filtered]"
359
+ return span
360
+
361
+
362
+ def _sentry_sdk_major() -> int:
363
+ """The installed sentry-sdk's major version, read from ``sentry_sdk.VERSION`` (``"3.0.0"`` is 3).
364
+
365
+ The major decides, not the presence of an option: sentry-sdk 2.76.0 accepts ``data_collection``
366
+ beside ``send_default_pii``, and passing it there would change what 2.x sends.
367
+
368
+ A module without a string ``VERSION`` is a stand-in, not an SDK: juniper-data's and juniper-cascor's
369
+ tests put an object with only ``init`` in ``sys.modules["sentry_sdk"]`` and assert 0.4.2's options,
370
+ and a ``MagicMock`` answers ``VERSION`` with another mock. Every real sentry-sdk defines ``VERSION`` as
371
+ a string, so a stand-in reads as 2, the options 0.4.2 passed to every SDK. A ``VERSION`` that does not
372
+ start with ASCII digits reads as 0, which no code path supports (``"\u00b2".isdigit()`` is True and
373
+ ``int`` refuses it): ``configure_sentry`` logs and initialises nothing, rather than raising at startup.
374
+ """
375
+ import sentry_sdk
376
+
377
+ version = getattr(sentry_sdk, "VERSION", None)
378
+ if not isinstance(version, str):
379
+ return 2
380
+ head = version.split(".", 1)[0]
381
+ return int(head) if head.isascii() and head.isdigit() else 0
382
+
383
+
384
+ def _data_collection(send_pii: bool) -> dict:
385
+ """sentry-sdk 3.x's ``data_collection``: what 2.x collected under ``send_default_pii=send_pii``, and no more.
386
+
387
+ 3.x collects by category, and its defaults collect almost everything (``data_collection.py``,
388
+ 3.0.0): user identity and the client's address, cookies, every request header, and every
389
+ frame's locals, with a substring denylist (``auth``, ``key``, ``token``, ``session`` ...)
390
+ replacing the values of the keys it matches.
391
+
392
+ - ``user_info`` is ``send_pii``: the client's address and the user, as ``send_default_pii``
393
+ governed them on 2.x.
394
+ - Cookies: without ``send_pii``, none, as 2.x attached none; with it, an allowlist with no terms,
395
+ which keeps every cookie's name and replaces every value -- what 0.4.2's hook made of the
396
+ cookies 2.x attached under ``send_default_pii=True``.
397
+ - Request headers: the SDK's denylist, also naming every header in
398
+ :data:`_SENTRY_SENSITIVE_HEADERS` and, without ``send_pii``, :data:`_SENTRY_ADDRESS_HEADERS`.
399
+ The terms are substrings, so each name matches itself.
400
+ - ``stack_frame_variables`` is off, as ``include_local_variables=False`` is on 2.x.
401
+
402
+ - Bodies, SQL parameters and redis arguments: none. Queue job arguments, GenAI and MCP inputs and
403
+ outputs, GraphQL documents and variables: only with ``send_pii``, as 2.x attached them. 3.x's
404
+ defaults collect every one of these whatever ``send_pii`` says.
405
+
406
+ The remaining categories keep the SDK's default. Query parameters are R-OBS-SC-3's to decide:
407
+ 3.x filters them with the same denylist where 2.x sent the query string raw.
408
+ """
409
+ header_terms = _SENTRY_SENSITIVE_HEADERS if send_pii else _SENTRY_SENSITIVE_HEADERS | _SENTRY_ADDRESS_HEADERS
410
+ return {
411
+ "user_info": send_pii,
412
+ "cookies": {"mode": "allowlist", "terms": []} if send_pii else {"mode": "off"},
413
+ "http_headers": {"request": {"mode": "denylist", "terms": sorted(header_terms)}},
414
+ "stack_frame_variables": False,
415
+ # No bodies: 2.x redacted a body's denylisted keys with the EventScrubber that 3.0.0 deleted,
416
+ # and 3.x also puts the raw body on every sampled server span (``http.request.body.data``).
417
+ # R-OBS-SC-3 decides bodies on both majors; until then 3.x sends none.
418
+ "http_bodies": [],
419
+ # 2.x never recorded SQL parameters by default (only under ``_experiments.record_sql_params``)
420
+ # and recorded a redis command's arguments only under ``send_default_pii``; 3.x records both.
421
+ "database_query_data": False,
422
+ # 2.x attached these only under ``send_default_pii``; 3.x's defaults attach them always.
423
+ "queues": send_pii,
424
+ "gen_ai": {"inputs": send_pii, "outputs": send_pii},
425
+ "mcp": {"inputs": send_pii, "outputs": send_pii},
426
+ "graphql": {"document": send_pii, "variables": send_pii},
427
+ }
428
+
429
+
430
+ def configure_sentry(
431
+ dsn: str | None,
432
+ service_name: str,
433
+ version: str,
434
+ *,
435
+ send_pii: bool = False,
436
+ traces_sample_rate: float = DEFAULT_SENTRY_TRACES_SAMPLE_RATE,
437
+ ) -> None:
438
+ """Initialize Sentry. No-op when ``dsn`` is None or empty.
439
+
440
+ Frame-local variables are never captured, and there is deliberately no
441
+ parameter to turn them back on: the value they add to a report is not
442
+ worth a secret in any frame's locals reaching a third-party service.
443
+
444
+ Works with sentry-sdk 2.x and 3.x; the installed major decides which
445
+ options are passed (see the module docstring).
446
+
447
+ Args:
448
+ dsn: Sentry DSN URL. Pass ``None`` or empty string to skip
449
+ initialization.
450
+ service_name: Service name for Sentry environment tag (used in
451
+ the ``release`` field as ``"<service_name>@<version>"``).
452
+ version: Application version string.
453
+ send_pii: Whether to send default PII (IP addresses, etc.) to
454
+ Sentry. **Defaults to False** (SEC-10); operators opt in
455
+ explicitly via per-service env vars when they accept the
456
+ risk. The hooks (``before_send`` for error events; on 2.x
457
+ ``before_send_transaction`` for transactions, on 3.x
458
+ ``before_send_span`` for spans) still scrub sensitive headers
459
+ and cookies regardless of this flag.
460
+ traces_sample_rate: Fraction of transactions (on 3.x, traces) to send (0.0–1.0).
461
+ """
462
+ if not dsn:
463
+ return
464
+
465
+ import sentry_sdk
466
+
467
+ major = _sentry_sdk_major()
468
+ if major not in (2, 3):
469
+ # Neither option set has been measured against this major, and consumers' own pins
470
+ # (``sentry-sdk>=2.0.0``) admit it: send nothing rather than guess.
471
+ _logging.getLogger(__name__).warning("sentry-sdk %s is not supported (2.x and 3.x are); Sentry is not initialised", sentry_sdk.VERSION)
472
+ return
473
+
474
+ options = {
475
+ "dsn": dsn,
476
+ "traces_sample_rate": traces_sample_rate,
477
+ "release": f"{service_name}@{version}",
478
+ "before_send": _strip_sensitive_headers,
479
+ }
480
+ if major == 3:
481
+ from sentry_sdk.integrations.logging import LoggingIntegration
482
+
483
+ options.update(
484
+ # PII, cookies, the extra header terms and no frame locals, by category.
485
+ data_collection=_data_collection(send_pii),
486
+ # Installed whatever ``traces_sample_rate`` says: at 0.0 the SDK still sends
487
+ # a span whose caller's ``sentry-trace`` header marks the trace sampled.
488
+ before_send_span=_strip_sensitive_span_attributes,
489
+ # 3.x installs no logging integration by default; 2.x's default made an ERROR
490
+ # record an error event, which 3.x's default ``event_level`` (None) does not.
491
+ integrations=[LoggingIntegration(event_level=_logging.ERROR)],
492
+ # 3.x defaults it to True (2.x: False): every message event, an ERROR record without an
493
+ # exception among them, would carry the whole thread stack with its source context.
494
+ attach_stacktrace=False,
495
+ )
496
+ else:
497
+ options.update(
498
+ send_default_pii=send_pii,
499
+ # Never snapshot frame locals into events: a local can hold a secret
500
+ # under any name (the canopy#683 finding's was ``candidate``).
501
+ include_local_variables=False,
502
+ enable_logs=True,
503
+ # The SDK never passes a transaction to ``before_send``. Without this, a
504
+ # ``send_pii=True`` transaction carries the raw ``X-API-Key`` (round-42 F2).
505
+ # Installed whatever ``traces_sample_rate`` says: even at 0.0 the SDK sends
506
+ # a transaction whose caller's ``sentry-trace`` header marks it sampled.
507
+ before_send_transaction=_strip_sensitive_headers,
508
+ )
509
+ sentry_sdk.init(**options)
510
+ # Recorded once ``init`` has returned: a call that raised, or that initialised nothing, leaves the
511
+ # previous client and its ``send_pii`` in place, and the two still agree.
512
+ global _send_pii, _configured_client
513
+ try:
514
+ client = sentry_sdk.get_global_scope().client
515
+ except Exception: # noqa: BLE001 — a stand-in ``sentry_sdk`` (the consumers' tests) has only ``init``
516
+ client = None
517
+ _send_pii, _configured_client = send_pii, client