juniper-observability 0.4.0__tar.gz → 0.4.2__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 (43) hide show
  1. juniper_observability-0.4.2/PKG-INFO +159 -0
  2. juniper_observability-0.4.2/README.md +121 -0
  3. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/_version.py +1 -1
  4. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/health/models.py +1 -1
  5. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/middleware/prometheus.py +1 -1
  6. juniper_observability-0.4.2/juniper_observability/middleware/request_id.py +89 -0
  7. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/prometheus.py +1 -1
  8. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/prometheus_helpers.py +9 -3
  9. juniper_observability-0.4.2/juniper_observability/py.typed +0 -0
  10. juniper_observability-0.4.2/juniper_observability/sentry.py +195 -0
  11. juniper_observability-0.4.2/juniper_observability.egg-info/PKG-INFO +159 -0
  12. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability.egg-info/SOURCES.txt +1 -0
  13. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability.egg-info/requires.txt +2 -2
  14. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/pyproject.toml +11 -3
  15. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_metrics_auth_middleware.py +1 -5
  16. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_prometheus_helpers.py +60 -1
  17. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_prometheus_middleware.py +1 -1
  18. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_public_api.py +52 -4
  19. juniper_observability-0.4.2/tests/test_request_id_middleware.py +186 -0
  20. juniper_observability-0.4.2/tests/test_sentry.py +628 -0
  21. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_testing_fixture.py +46 -2
  22. juniper_observability-0.4.0/PKG-INFO +0 -201
  23. juniper_observability-0.4.0/README.md +0 -164
  24. juniper_observability-0.4.0/juniper_observability/middleware/request_id.py +0 -43
  25. juniper_observability-0.4.0/juniper_observability/sentry.py +0 -75
  26. juniper_observability-0.4.0/juniper_observability.egg-info/PKG-INFO +0 -201
  27. juniper_observability-0.4.0/tests/test_request_id_middleware.py +0 -69
  28. juniper_observability-0.4.0/tests/test_sentry.py +0 -100
  29. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/__init__.py +0 -0
  30. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/constants.py +0 -0
  31. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/health/__init__.py +0 -0
  32. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/health/probe.py +0 -0
  33. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/logging.py +0 -0
  34. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/middleware/__init__.py +0 -0
  35. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/middleware/metrics_auth.py +0 -0
  36. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability/testing.py +0 -0
  37. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability.egg-info/dependency_links.txt +0 -0
  38. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/juniper_observability.egg-info/top_level.txt +0 -0
  39. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/setup.cfg +0 -0
  40. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_health_models.py +0 -0
  41. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_health_probe.py +0 -0
  42. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_logging.py +0 -0
  43. {juniper_observability-0.4.0 → juniper_observability-0.4.2}/tests/test_prometheus_utils.py +0 -0
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: juniper-observability
3
+ Version: 0.4.2
4
+ Summary: Shared observability primitives (health models, logging, middleware, Sentry, Prometheus) for the Juniper ML platform
5
+ Author: Paul Calnon
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/pcalnon/juniper-ml
8
+ Project-URL: Repository, https://github.com/pcalnon/juniper-ml
9
+ Project-URL: Issues, https://github.com/pcalnon/juniper-ml/issues
10
+ Keywords: juniper,observability,health,metrics,logging
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: System :: Monitoring
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.12
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: pydantic>=2.0
23
+ Requires-Dist: starlette>=0.27
24
+ Provides-Extra: prometheus
25
+ Requires-Dist: prometheus-client>=0.20.0; extra == "prometheus"
26
+ Provides-Extra: sentry
27
+ Requires-Dist: sentry-sdk[fastapi]>=2.35.0; extra == "sentry"
28
+ Provides-Extra: all
29
+ Requires-Dist: juniper-observability[prometheus,sentry]; extra == "all"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=8.0; extra == "test"
32
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
33
+ Requires-Dist: pytest-cov>=5.0; extra == "test"
34
+ Requires-Dist: httpx>=0.27; extra == "test"
35
+ Requires-Dist: fastapi>=0.110; extra == "test"
36
+ Requires-Dist: prometheus-client>=0.20.0; extra == "test"
37
+ Requires-Dist: sentry-sdk[fastapi]>=2.35.0; extra == "test"
38
+
39
+ # juniper-observability
40
+
41
+ [![PyPI](https://img.shields.io/pypi/v/juniper-observability)](https://pypi.org/project/juniper-observability/)
42
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue)](https://www.python.org/)
43
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](../LICENSE)
44
+
45
+ **Shared observability primitives for the Juniper platform — health models, structured logging,
46
+ middleware, and crash-safe Prometheus collector registration.**
47
+
48
+ `juniper-observability` is the single place every Juniper service gets its cross-cutting observability
49
+ wiring, so each service doesn't re-implement it: Pydantic health-response models for the
50
+ `/v1/health/ready` endpoint, structured-JSON logging with `request_id` propagation, the Starlette
51
+ `RequestIdMiddleware` and `PrometheusMiddleware`, **idempotent `prometheus_client` collector helpers**,
52
+ the matching pytest reset fixture, and Sentry initialisation.
53
+
54
+ The collector helpers are the headline. Registering a `Counter` / `Gauge` / `Histogram` / … twice —
55
+ across a module reload or a pytest-fixture reset — normally raises
56
+ `Duplicated timeseries in CollectorRegistry`. `register_or_reuse` adopts the existing collector
57
+ instead, so registration is safe to repeat.
58
+
59
+ > **Part of the Juniper platform.** juniper-observability is the shared observability layer of
60
+ > [Juniper](https://github.com/pcalnon/juniper-ml) — a multi-package ML research platform built around
61
+ > constructive (Cascade-Correlation) and recurrent neural networks. It's a small infrastructure
62
+ > library; you don't need the rest of the platform to use it.
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install juniper-observability # core
68
+ pip install "juniper-observability[prometheus]" # + Prometheus middleware/utilities
69
+ pip install "juniper-observability[sentry]" # + Sentry init
70
+ pip install "juniper-observability[all]" # everything
71
+ ```
72
+
73
+ It is also pulled in by the meta-package's `juniper-ml[tools]` and `juniper-ml[all]` extras.
74
+
75
+ ## Quick start
76
+
77
+ ```python
78
+ from prometheus_client import CollectorRegistry, Counter
79
+ from juniper_observability import register_or_reuse
80
+
81
+ registry = CollectorRegistry()
82
+ c1 = register_or_reuse(Counter, "demo_total", "demo counter", registry=registry)
83
+ c2 = register_or_reuse(Counter, "demo_total", "demo counter", registry=registry)
84
+ assert c1 is c2 # the second call adopts the existing collector — no exception
85
+ ```
86
+
87
+ For tests that touch collector state, use the canonical reset fixture:
88
+
89
+ ```python
90
+ from juniper_observability.testing import reset_prometheus_registry # pytest fixture
91
+ ```
92
+
93
+ ## What's in the box
94
+
95
+ | Surface | What it gives you |
96
+ |---|---|
97
+ | `register_or_reuse` / `register_fresh` / `register_info_or_update` / `lazy_register_or_reuse` | Idempotent `prometheus_client` collector registration (adopt-existing is the default). |
98
+ | `testing.reset_prometheus_registry` | Pytest fixture that resets collector state between tests. |
99
+ | `RequestIdMiddleware`, `PrometheusMiddleware` | Starlette middlewares applied across the service fleet. |
100
+ | Health-response models | Pydantic models for the `/v1/health/ready` endpoint. |
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`. |
103
+
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
+
106
+ Operator notes: [juniper-ml REFERENCE](../docs/REFERENCE.md#non-ascii-api-keys-and-sentry-frame-locals).
107
+
108
+ **Per-service metrics stay in each repo.** This package exposes only *cross-cutting* infrastructure;
109
+ service-specific metric definitions (training-loop counters, dataset-gen histograms, websocket gauges)
110
+ live in their owning repo and register via `register_or_reuse` against `prometheus_client.REGISTRY`.
111
+
112
+ ## Consumers
113
+
114
+ The service repos — [`juniper-data`](https://github.com/pcalnon/juniper-data),
115
+ [`juniper-cascor`](https://github.com/pcalnon/juniper-cascor),
116
+ [`juniper-canopy`](https://github.com/pcalnon/juniper-canopy) — import the middlewares, health models,
117
+ and collector helpers (pin `>=0.2.0`). The client libraries
118
+ ([`juniper-data-client`](https://github.com/pcalnon/juniper-data-client),
119
+ [`juniper-cascor-client`](https://github.com/pcalnon/juniper-cascor-client)) pull it in via their
120
+ `[observability]` extra for `X-Request-ID` propagation and Prometheus counters.
121
+
122
+ ## Status
123
+
124
+ **Live** on PyPI, published independently of the meta-package on `juniper-observability-v*` tags. The
125
+ 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.
129
+
130
+ ### Compatibility policy — pinning, not deprecation cycles
131
+
132
+ This package ships **no deprecation machinery**: no `DeprecationWarning`, no
133
+ `PendingDeprecationWarning`, no legacy aliases. That is deliberate, not an oversight
134
+ (defect-register `APD-ECO-007`).
135
+
136
+ While pre-1.0, compatibility is managed by **external pinning** — consumers pin a floor
137
+ and a ceiling, so each `0.x` is a compatibility boundary and a breaking change is
138
+ absorbed by a ceiling raise the consumer performs deliberately. That holds while the
139
+ consumer set is a known, enumerable handful of first-party repositories.
140
+
141
+ **What would change this:** a third-party dependant, or 1.0 — at which point the
142
+ consumer set stops being enumerable and a census stops being a sufficient substitute
143
+ for a deprecation cycle. When that happens, reuse the implementations this ecosystem
144
+ already has rather than writing a third:
145
+ `juniper_config_tools.env_with_legacy_alias` for env-var renames, and the
146
+ `juniper-data-client` alias pattern (a `DeprecationWarning` with a correct `stacklevel`
147
+ and a **dated** removal window) for API renames. Re-derivation is exactly how the
148
+ env-var lookup drifted across three services before it was consolidated.
149
+
150
+ ## Design
151
+
152
+ Part of the [Juniper](https://github.com/pcalnon) ML research platform. Rationale and history:
153
+
154
+ - [`register_or_reuse` helper design + migration history](../notes/observability/JUNIPER_2026-05-05_JUNIPER-ML_REGISTER-OR-REUSE-HELPER-DESIGN.md)
155
+ - [METRICS-MON R2.1 shared-observability design](../notes/legacy/METRICS_MONITORING_R2.1_SHARED_OBSERVABILITY_DESIGN_2026-04-28.md) (archived)
156
+
157
+ ## License
158
+
159
+ MIT — see [LICENSE](../LICENSE).
@@ -0,0 +1,121 @@
1
+ # juniper-observability
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/juniper-observability)](https://pypi.org/project/juniper-observability/)
4
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue)](https://www.python.org/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](../LICENSE)
6
+
7
+ **Shared observability primitives for the Juniper platform — health models, structured logging,
8
+ middleware, and crash-safe Prometheus collector registration.**
9
+
10
+ `juniper-observability` is the single place every Juniper service gets its cross-cutting observability
11
+ wiring, so each service doesn't re-implement it: Pydantic health-response models for the
12
+ `/v1/health/ready` endpoint, structured-JSON logging with `request_id` propagation, the Starlette
13
+ `RequestIdMiddleware` and `PrometheusMiddleware`, **idempotent `prometheus_client` collector helpers**,
14
+ the matching pytest reset fixture, and Sentry initialisation.
15
+
16
+ The collector helpers are the headline. Registering a `Counter` / `Gauge` / `Histogram` / … twice —
17
+ across a module reload or a pytest-fixture reset — normally raises
18
+ `Duplicated timeseries in CollectorRegistry`. `register_or_reuse` adopts the existing collector
19
+ instead, so registration is safe to repeat.
20
+
21
+ > **Part of the Juniper platform.** juniper-observability is the shared observability layer of
22
+ > [Juniper](https://github.com/pcalnon/juniper-ml) — a multi-package ML research platform built around
23
+ > constructive (Cascade-Correlation) and recurrent neural networks. It's a small infrastructure
24
+ > library; you don't need the rest of the platform to use it.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install juniper-observability # core
30
+ pip install "juniper-observability[prometheus]" # + Prometheus middleware/utilities
31
+ pip install "juniper-observability[sentry]" # + Sentry init
32
+ pip install "juniper-observability[all]" # everything
33
+ ```
34
+
35
+ It is also pulled in by the meta-package's `juniper-ml[tools]` and `juniper-ml[all]` extras.
36
+
37
+ ## Quick start
38
+
39
+ ```python
40
+ from prometheus_client import CollectorRegistry, Counter
41
+ from juniper_observability import register_or_reuse
42
+
43
+ registry = CollectorRegistry()
44
+ c1 = register_or_reuse(Counter, "demo_total", "demo counter", registry=registry)
45
+ c2 = register_or_reuse(Counter, "demo_total", "demo counter", registry=registry)
46
+ assert c1 is c2 # the second call adopts the existing collector — no exception
47
+ ```
48
+
49
+ For tests that touch collector state, use the canonical reset fixture:
50
+
51
+ ```python
52
+ from juniper_observability.testing import reset_prometheus_registry # pytest fixture
53
+ ```
54
+
55
+ ## What's in the box
56
+
57
+ | Surface | What it gives you |
58
+ |---|---|
59
+ | `register_or_reuse` / `register_fresh` / `register_info_or_update` / `lazy_register_or_reuse` | Idempotent `prometheus_client` collector registration (adopt-existing is the default). |
60
+ | `testing.reset_prometheus_registry` | Pytest fixture that resets collector state between tests. |
61
+ | `RequestIdMiddleware`, `PrometheusMiddleware` | Starlette middlewares applied across the service fleet. |
62
+ | Health-response models | Pydantic models for the `/v1/health/ready` endpoint. |
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`. |
65
+
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
+
68
+ Operator notes: [juniper-ml REFERENCE](../docs/REFERENCE.md#non-ascii-api-keys-and-sentry-frame-locals).
69
+
70
+ **Per-service metrics stay in each repo.** This package exposes only *cross-cutting* infrastructure;
71
+ service-specific metric definitions (training-loop counters, dataset-gen histograms, websocket gauges)
72
+ live in their owning repo and register via `register_or_reuse` against `prometheus_client.REGISTRY`.
73
+
74
+ ## Consumers
75
+
76
+ The service repos — [`juniper-data`](https://github.com/pcalnon/juniper-data),
77
+ [`juniper-cascor`](https://github.com/pcalnon/juniper-cascor),
78
+ [`juniper-canopy`](https://github.com/pcalnon/juniper-canopy) — import the middlewares, health models,
79
+ and collector helpers (pin `>=0.2.0`). The client libraries
80
+ ([`juniper-data-client`](https://github.com/pcalnon/juniper-data-client),
81
+ [`juniper-cascor-client`](https://github.com/pcalnon/juniper-cascor-client)) pull it in via their
82
+ `[observability]` extra for `X-Request-ID` propagation and Prometheus counters.
83
+
84
+ ## Status
85
+
86
+ **Live** on PyPI, published independently of the meta-package on `juniper-observability-v*` tags. The
87
+ 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.
91
+
92
+ ### Compatibility policy — pinning, not deprecation cycles
93
+
94
+ This package ships **no deprecation machinery**: no `DeprecationWarning`, no
95
+ `PendingDeprecationWarning`, no legacy aliases. That is deliberate, not an oversight
96
+ (defect-register `APD-ECO-007`).
97
+
98
+ While pre-1.0, compatibility is managed by **external pinning** — consumers pin a floor
99
+ and a ceiling, so each `0.x` is a compatibility boundary and a breaking change is
100
+ absorbed by a ceiling raise the consumer performs deliberately. That holds while the
101
+ consumer set is a known, enumerable handful of first-party repositories.
102
+
103
+ **What would change this:** a third-party dependant, or 1.0 — at which point the
104
+ consumer set stops being enumerable and a census stops being a sufficient substitute
105
+ for a deprecation cycle. When that happens, reuse the implementations this ecosystem
106
+ already has rather than writing a third:
107
+ `juniper_config_tools.env_with_legacy_alias` for env-var renames, and the
108
+ `juniper-data-client` alias pattern (a `DeprecationWarning` with a correct `stacklevel`
109
+ and a **dated** removal window) for API renames. Re-derivation is exactly how the
110
+ env-var lookup drifted across three services before it was consolidated.
111
+
112
+ ## Design
113
+
114
+ Part of the [Juniper](https://github.com/pcalnon) ML research platform. Rationale and history:
115
+
116
+ - [`register_or_reuse` helper design + migration history](../notes/observability/JUNIPER_2026-05-05_JUNIPER-ML_REGISTER-OR-REUSE-HELPER-DESIGN.md)
117
+ - [METRICS-MON R2.1 shared-observability design](../notes/legacy/METRICS_MONITORING_R2.1_SHARED_OBSERVABILITY_DESIGN_2026-04-28.md) (archived)
118
+
119
+ ## License
120
+
121
+ MIT — see [LICENSE](../LICENSE).
@@ -1,3 +1,3 @@
1
1
  """Single source of truth for the package version."""
2
2
 
3
- __version__ = "0.4.0"
3
+ __version__ = "0.4.2"
@@ -34,7 +34,7 @@ class ReadinessResponse(BaseModel):
34
34
  status: Literal["ready", "degraded", "not_ready"]
35
35
  version: str
36
36
  service: str
37
- # Build provenance (juniper-ml notes/BUILD_PROVENANCE_DESIGN_2026-06-14.md):
37
+ # Build provenance (juniper-ml notes/JUNIPER_2026-06-14_JUNIPER-ECOSYSTEM_BUILD-PROVENANCE-DESIGN.md):
38
38
  # the source git SHA and ISO-8601 build timestamp baked into the image
39
39
  # at build time. ``None`` when the service runs outside a provenance-
40
40
  # stamped image (local dev / pre-rollout). Surfaced here so stale-image
@@ -44,7 +44,7 @@ class PrometheusMiddleware(BaseHTTPMiddleware):
44
44
  # duplicate registration (test sessions that re-create the app,
45
45
  # in-process service restarts) instead of crashing app startup
46
46
  # with ``ValueError: Duplicated timeseries``. See
47
- # ``notes/observability/REGISTER_OR_REUSE_HELPER_DESIGN_2026-05-05.md``
47
+ # ``notes/observability/JUNIPER_2026-05-05_JUNIPER-ML_REGISTER-OR-REUSE-HELPER-DESIGN.md``
48
48
  # in juniper-ml for the full rationale.
49
49
  self._request_count = register_or_reuse(
50
50
  Counter,
@@ -0,0 +1,89 @@
1
+ """Request-ID propagation middleware.
2
+
3
+ Injects an ``X-Request-ID`` header into every response and stores the
4
+ value in a ContextVar so async handlers and log records can correlate
5
+ to the originating HTTP request without threading the ID through every
6
+ call.
7
+
8
+ Inbound values are validated before propagation (APD-OBS-001). The header is
9
+ attacker-controlled, and the value flows into a process-wide ContextVar that any
10
+ consumer may write to a line-oriented sink and that is echoed back on the response.
11
+
12
+ Today that is contained -- but only *incidentally*, by machinery this package does
13
+ not own or assert. h11 caps the entire request head at
14
+ ``max_incomplete_event_size`` (16384 by default, and uvicorn leaves it alone), so a
15
+ multi-megabyte header never reaches ASGI; and h11 rejects CR/LF in header values
16
+ outright, so the response echo is not a header-injection vector. Both of those are
17
+ h11 defaults. Validating on ingress means the guarantee belongs here instead of
18
+ being borrowed.
19
+ """
20
+
21
+ import re
22
+ import uuid
23
+ from contextvars import ContextVar
24
+
25
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
26
+ from starlette.requests import Request
27
+ from starlette.responses import Response
28
+
29
+ from juniper_observability.constants import HEADER_X_REQUEST_ID
30
+
31
+ # Public ContextVar; ``JuniperJsonFormatter`` reads from it to embed the
32
+ # request ID in every log record emitted during the request scope.
33
+ request_id_var: ContextVar[str] = ContextVar("request_id", default="")
34
+
35
+ #: Maximum accepted inbound request-ID length. Generous next to the 36 characters of
36
+ #: a UUID4 and the 55 of a W3C ``traceparent``, but small enough that the value
37
+ #: cannot meaningfully bloat a log line it is copied into.
38
+ MAX_REQUEST_ID_LENGTH = 128
39
+
40
+ #: Characters accepted in an inbound request ID. Covers UUIDs, ULIDs, W3C trace
41
+ #: identifiers and the ``service:id`` shapes services use, while excluding
42
+ #: whitespace, control characters and anything with meaning to a log or terminal
43
+ #: consumer. An allowlist rather than a denylist on purpose: the set of characters
44
+ #: that are safe in *every* downstream sink is far easier to enumerate correctly
45
+ #: than the set that is dangerous in any of them.
46
+ _REQUEST_ID_RE = re.compile(r"\A[A-Za-z0-9._:-]+\Z")
47
+
48
+
49
+ def is_valid_request_id(value: str) -> bool:
50
+ """Whether an inbound ``X-Request-ID`` may be propagated as-is.
51
+
52
+ Args:
53
+ value: The raw header value.
54
+
55
+ Returns:
56
+ True when the value is within :data:`MAX_REQUEST_ID_LENGTH` and contains only
57
+ allowlisted characters.
58
+ """
59
+ return bool(value) and len(value) <= MAX_REQUEST_ID_LENGTH and bool(_REQUEST_ID_RE.match(value))
60
+
61
+
62
+ class RequestIdMiddleware(BaseHTTPMiddleware):
63
+ """Injects ``X-Request-ID`` into ContextVar and response header.
64
+
65
+ If the request carries an inbound ``X-Request-ID`` header, that
66
+ value is propagated; otherwise a fresh UUID4 is generated. The
67
+ header is always echoed back on the response.
68
+ """
69
+
70
+ async def dispatch(
71
+ self,
72
+ request: Request,
73
+ call_next: RequestResponseEndpoint,
74
+ ) -> Response:
75
+ inbound = request.headers.get(HEADER_X_REQUEST_ID)
76
+ # Replace rather than sanitize. Stripping offending characters would
77
+ # propagate a value the client never sent, so the ID in the logs would
78
+ # correlate to nothing on either side; a fresh UUID is at least honestly
79
+ # this server's own. Rejection is deliberately silent -- logging it would
80
+ # hand an attacker a log-flood lever, which is the very class this guard
81
+ # exists to bound.
82
+ rid = inbound if inbound is not None and is_valid_request_id(inbound) else str(uuid.uuid4())
83
+ token = request_id_var.set(rid)
84
+ try:
85
+ response = await call_next(request)
86
+ response.headers[HEADER_X_REQUEST_ID] = rid
87
+ return response
88
+ finally:
89
+ request_id_var.reset(token)
@@ -37,7 +37,7 @@ def set_build_info(
37
37
 
38
38
  Always carries ``version`` + ``python_version``. When ``git_sha`` /
39
39
  ``build_date`` are supplied (the build-provenance path — see juniper-ml
40
- ``notes/BUILD_PROVENANCE_DESIGN_2026-06-14.md``) they are added as
40
+ ``notes/JUNIPER_2026-06-14_JUNIPER-ECOSYSTEM_BUILD-PROVENANCE-DESIGN.md``) they are added as
41
41
  additional Info labels so the deployed source revision is visible in
42
42
  Prometheus/Grafana. They are omitted when ``None`` (e.g. local dev or
43
43
  a pre-rollout image), keeping the metric clean rather than emitting
@@ -13,7 +13,7 @@ sites across 5 repos, with two subtly different implementations
13
13
  ("adopt existing" vs "drop and recreate") in the wild.
14
14
 
15
15
  These helpers consolidate the pattern. See
16
- ``notes/observability/REGISTER_OR_REUSE_HELPER_DESIGN_2026-05-05.md``
16
+ ``notes/observability/JUNIPER_2026-05-05_JUNIPER-ML_REGISTER-OR-REUSE-HELPER-DESIGN.md``
17
17
  in the juniper-ml repo for the full analysis, rationale, and
18
18
  migration plan.
19
19
 
@@ -43,7 +43,13 @@ to surface unexpected re-registrations can wrap.
43
43
  from __future__ import annotations
44
44
 
45
45
  import threading
46
- from typing import Any, Callable, TypeVar
46
+ from typing import TYPE_CHECKING, Any, Callable, TypeVar
47
+
48
+ if TYPE_CHECKING: # pragma: no cover - typing only
49
+ # ``prometheus_client`` is an optional extra, so it must never be imported
50
+ # at runtime here. ``from __future__ import annotations`` makes the
51
+ # annotation a string, so this import costs nothing outside a type checker.
52
+ from prometheus_client import Info
47
53
 
48
54
  T = TypeVar("T")
49
55
 
@@ -215,7 +221,7 @@ def register_info_or_update(
215
221
  name: str,
216
222
  description: str,
217
223
  **info_labels: str,
218
- ) -> Any:
224
+ ) -> Info:
219
225
  """Register a ``prometheus_client.Info`` collector and set its labels.
220
226
 
221
227
  ``Info`` is the one collector type with a two-step registration:
@@ -0,0 +1,195 @@
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 0.4.3, to be designed and validated on
45
+ 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``.
48
+
49
+ ``configure_sentry`` is a no-op when ``dsn`` is ``None`` or the empty
50
+ string, so consumers can call it unconditionally during startup.
51
+ """
52
+
53
+ DEFAULT_SENTRY_TRACES_SAMPLE_RATE = 0.1
54
+
55
+ # SEC-10: header names that may carry API keys, credentials or session identifiers, compared
56
+ # lower-case. 0.4.2 added the last four. ``sec-websocket-protocol`` is where juniper-canopy's
57
+ # server reads a WebSocket key (``bearer, <key>``) when its opt-in ``ws_auth_enabled`` is on;
58
+ # it and the two CSRF tokens are on neither of the SDK's own lists, so they reached Sentry even
59
+ # under the default ``send_pii=False``. sentry-sdk 2.35.0 filters ``proxy-authorization`` in
60
+ # neither mode (2.73.0 does, in both).
61
+ _SENTRY_SENSITIVE_HEADERS = frozenset(
62
+ {
63
+ "x-api-key",
64
+ "authorization",
65
+ "cookie",
66
+ "proxy-authorization",
67
+ "sec-websocket-protocol",
68
+ "x-csrf-token",
69
+ "x-xsrf-token",
70
+ }
71
+ )
72
+
73
+ # Event interfaces whose ``values`` entries each carry their own ``stacktrace``
74
+ # (an event may also carry one top-level ``stacktrace``, e.g. a message
75
+ # captured with ``attach_stacktrace``).
76
+ _SENTRY_STACKTRACE_INTERFACES = ("exception", "threads")
77
+
78
+
79
+ def _strip_frame_local_variables(event):
80
+ """Delete ``vars`` from every stack frame of a Sentry event, in place.
81
+
82
+ Covers every place the Sentry protocol puts frames: each
83
+ ``exception.values[*].stacktrace`` (one per exception in a chain), each
84
+ ``threads.values[*].stacktrace``, and the top-level ``stacktrace``.
85
+ Anything that is not the expected dict/list shape is skipped rather than
86
+ raised on -- a ``before_send`` hook that raises drops the event, and an
87
+ unreadable event is no reason to lose the report.
88
+ """
89
+ stacktraces = [event.get("stacktrace")]
90
+ for interface in _SENTRY_STACKTRACE_INTERFACES:
91
+ container = event.get(interface)
92
+ values = container.get("values") if isinstance(container, dict) else None
93
+ if isinstance(values, list):
94
+ stacktraces.extend(value.get("stacktrace") for value in values if isinstance(value, dict))
95
+ for stacktrace in stacktraces:
96
+ frames = stacktrace.get("frames") if isinstance(stacktrace, dict) else None
97
+ if isinstance(frames, list):
98
+ for frame in frames:
99
+ if isinstance(frame, dict):
100
+ frame.pop("vars", None)
101
+
102
+
103
+ def _strip_sensitive_headers(event, hint): # noqa: ARG001 — Sentry hook signature
104
+ """Redact sensitive request headers and cookies, and drop frame-local variables.
105
+
106
+ Sentry calls this via ``before_send`` for every error event and via
107
+ ``before_send_transaction`` for every transaction; a transaction never
108
+ reaches ``before_send``. The header filter only rewrites keys in
109
+ :data:`_SENTRY_SENSITIVE_HEADERS` so non-sensitive diagnostic headers
110
+ (user-agent, trace IDs, etc.) still reach Sentry unchanged. Every value
111
+ of a non-empty ``request.cookies`` dict is replaced and its names are
112
+ kept: it is the ``Cookie`` header parsed into names and values, and no
113
+ list of cookie names can say which of them carries a session. A
114
+ non-empty ``cookies`` of any other shape (the protocol also allows a raw
115
+ header string or a list of pairs) is dropped rather than rewritten: the
116
+ SDK's integrations produce the dict, a string would have to be parsed,
117
+ and the protocol reads a string as a raw ``Cookie`` header, which a bare
118
+ ``[Filtered]`` is not.
119
+
120
+ It also deletes every frame's ``vars`` (:func:`_strip_frame_local_variables`).
121
+ ``configure_sentry`` already passes ``include_local_variables=False``, so
122
+ the SDK's own capture paths attach none; this is the backstop for
123
+ anything that adds them regardless. The name is kept although the hook
124
+ now does more than headers, because juniper-data and juniper-cascor import
125
+ it by this name (cascor's ``main.py`` passes it to its own
126
+ ``sentry_sdk.init``), and a rename would break those imports.
127
+ """
128
+ if not isinstance(event, dict):
129
+ return event
130
+ request_data = event.get("request", {})
131
+ headers = request_data.get("headers", {}) if isinstance(request_data, dict) else {}
132
+ if isinstance(headers, dict):
133
+ for key in list(headers.keys()):
134
+ if key.lower() in _SENTRY_SENSITIVE_HEADERS:
135
+ headers[key] = "[Filtered]"
136
+ if isinstance(request_data, dict):
137
+ cookies = request_data.get("cookies")
138
+ if isinstance(cookies, dict):
139
+ if cookies:
140
+ request_data["cookies"] = dict.fromkeys(cookies, "[Filtered]")
141
+ elif cookies:
142
+ del request_data["cookies"]
143
+ _strip_frame_local_variables(event)
144
+ return event
145
+
146
+
147
+ def configure_sentry(
148
+ dsn: str | None,
149
+ service_name: str,
150
+ version: str,
151
+ *,
152
+ send_pii: bool = False,
153
+ traces_sample_rate: float = DEFAULT_SENTRY_TRACES_SAMPLE_RATE,
154
+ ) -> None:
155
+ """Initialize Sentry. No-op when ``dsn`` is None or empty.
156
+
157
+ Frame-local variables are never captured, and there is deliberately no
158
+ parameter to turn them back on: the value they add to a report is not
159
+ worth a secret in any frame's locals reaching a third-party service.
160
+
161
+ Args:
162
+ dsn: Sentry DSN URL. Pass ``None`` or empty string to skip
163
+ initialization.
164
+ service_name: Service name for Sentry environment tag (used in
165
+ the ``release`` field as ``"<service_name>@<version>"``).
166
+ version: Application version string.
167
+ send_pii: Whether to send default PII (IP addresses, etc.) to
168
+ Sentry. **Defaults to False** (SEC-10); operators opt in
169
+ explicitly via per-service env vars when they accept the
170
+ risk. The hook (``before_send`` for error events,
171
+ ``before_send_transaction`` for transactions) still scrubs
172
+ sensitive headers and cookies regardless of this flag.
173
+ traces_sample_rate: Fraction of transactions to send (0.0–1.0).
174
+ """
175
+ if not dsn:
176
+ return
177
+
178
+ import sentry_sdk
179
+
180
+ sentry_sdk.init(
181
+ dsn=dsn,
182
+ send_default_pii=send_pii,
183
+ # Never snapshot frame locals into events: a local can hold a secret
184
+ # under any name (the canopy#683 finding's was ``candidate``).
185
+ include_local_variables=False,
186
+ enable_logs=True,
187
+ traces_sample_rate=traces_sample_rate,
188
+ release=f"{service_name}@{version}",
189
+ before_send=_strip_sensitive_headers,
190
+ # The SDK never passes a transaction to ``before_send``. Without this, a
191
+ # ``send_pii=True`` transaction carries the raw ``X-API-Key`` (round-42 F2).
192
+ # Installed whatever ``traces_sample_rate`` says: even at 0.0 the SDK sends
193
+ # a transaction whose caller's ``sentry-trace`` header marks it sampled.
194
+ before_send_transaction=_strip_sensitive_headers,
195
+ )