authzai 0.2.0__py3-none-any.whl
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.
- agentic_auth/__init__.py +8 -0
- agentic_auth/_extras.py +24 -0
- agentic_auth/api/__init__.py +0 -0
- agentic_auth/api/deps.py +112 -0
- agentic_auth/api/errors.py +51 -0
- agentic_auth/api/responses.py +38 -0
- agentic_auth/api/service_deps.py +113 -0
- agentic_auth/api/v1/__init__.py +0 -0
- agentic_auth/api/v1/agents.py +88 -0
- agentic_auth/api/v1/audit.py +67 -0
- agentic_auth/api/v1/authorize.py +439 -0
- agentic_auth/api/v1/consent.py +21 -0
- agentic_auth/api/v1/decisions.py +43 -0
- agentic_auth/api/v1/enrollment.py +48 -0
- agentic_auth/api/v1/identity.py +97 -0
- agentic_auth/api/v1/jwks.py +21 -0
- agentic_auth/api/v1/manifests.py +68 -0
- agentic_auth/api/v1/scopes.py +22 -0
- agentic_auth/api/v1/token.py +203 -0
- agentic_auth/api/v1/transaction.py +94 -0
- agentic_auth/boundary/__init__.py +26 -0
- agentic_auth/boundary/guarantee.py +96 -0
- agentic_auth/cli/__init__.py +27 -0
- agentic_auth/cli/audit.py +130 -0
- agentic_auth/cli/drift.py +164 -0
- agentic_auth/cli/drift_render.py +148 -0
- agentic_auth/cli/identity.py +63 -0
- agentic_auth/cli/manifest.py +275 -0
- agentic_auth/config.py +182 -0
- agentic_auth/db.py +49 -0
- agentic_auth/embedded/__init__.py +427 -0
- agentic_auth/embedded/_schema.py +8 -0
- agentic_auth/embedded/_transport.py +39 -0
- agentic_auth/embedded/capabilities.py +34 -0
- agentic_auth/embedded/export.py +86 -0
- agentic_auth/embedded/idp.py +78 -0
- agentic_auth/embedded/store.py +240 -0
- agentic_auth/errors.py +145 -0
- agentic_auth/main.py +141 -0
- agentic_auth/models/__init__.py +70 -0
- agentic_auth/models/agent.py +58 -0
- agentic_auth/models/audit_decision.py +199 -0
- agentic_auth/models/compiled_policy.py +28 -0
- agentic_auth/models/manifest.py +96 -0
- agentic_auth/models/reconciliation_report.py +27 -0
- agentic_auth/models/sandbox_run.py +93 -0
- agentic_auth/models/session.py +63 -0
- agentic_auth/models/step_up_grant.py +106 -0
- agentic_auth/models/transaction_token.py +73 -0
- agentic_auth/models/trust_anchor.py +59 -0
- agentic_auth/models/types.py +95 -0
- agentic_auth/observability/__init__.py +370 -0
- agentic_auth/observability/config.py +137 -0
- agentic_auth/observability/context.py +128 -0
- agentic_auth/observability/ids.py +122 -0
- agentic_auth/observability/logs.py +191 -0
- agentic_auth/observability/pep.py +169 -0
- agentic_auth/observability/spans.py +225 -0
- agentic_auth/observability/surface.py +286 -0
- agentic_auth/observability/tracing.py +167 -0
- agentic_auth/redis.py +27 -0
- agentic_auth/repositories/__init__.py +0 -0
- agentic_auth/repositories/agents.py +96 -0
- agentic_auth/repositories/audit_decisions.py +152 -0
- agentic_auth/repositories/compiled_policies.py +72 -0
- agentic_auth/repositories/manifests.py +149 -0
- agentic_auth/repositories/reconciliation_reports.py +40 -0
- agentic_auth/repositories/sessions.py +41 -0
- agentic_auth/repositories/transaction_tokens.py +60 -0
- agentic_auth/repositories/trust_anchors.py +150 -0
- agentic_auth/runtime.py +81 -0
- agentic_auth/schemas/__init__.py +0 -0
- agentic_auth/schemas/agent.py +58 -0
- agentic_auth/schemas/audit.py +207 -0
- agentic_auth/schemas/authorize.py +205 -0
- agentic_auth/schemas/common.py +40 -0
- agentic_auth/schemas/consent.py +74 -0
- agentic_auth/schemas/dag.py +39 -0
- agentic_auth/schemas/edge_trace.py +166 -0
- agentic_auth/schemas/identity.py +152 -0
- agentic_auth/schemas/manifest.py +117 -0
- agentic_auth/schemas/manifest_api.py +38 -0
- agentic_auth/schemas/reconciliation.py +49 -0
- agentic_auth/schemas/token.py +122 -0
- agentic_auth/schemas/transaction.py +28 -0
- agentic_auth/sdk/__init__.py +114 -0
- agentic_auth/sdk/client.py +677 -0
- agentic_auth/sdk/context.py +95 -0
- agentic_auth/sdk/drift.py +118 -0
- agentic_auth/sdk/errors.py +147 -0
- agentic_auth/sdk/identity.py +162 -0
- agentic_auth/sdk/planes.py +362 -0
- agentic_auth/sdk/provenance.py +63 -0
- agentic_auth/services/__init__.py +0 -0
- agentic_auth/services/anchors.py +81 -0
- agentic_auth/services/audit.py +222 -0
- agentic_auth/services/audit_chain.py +144 -0
- agentic_auth/services/audit_cursor.py +55 -0
- agentic_auth/services/catalog_service.py +58 -0
- agentic_auth/services/chain_query.py +152 -0
- agentic_auth/services/dag_compiler.py +199 -0
- agentic_auth/services/decision_cache.py +123 -0
- agentic_auth/services/decision_history.py +71 -0
- agentic_auth/services/discovery.py +95 -0
- agentic_auth/services/drift.py +330 -0
- agentic_auth/services/edge_rules.py +62 -0
- agentic_auth/services/edge_trace.py +198 -0
- agentic_auth/services/enrollment.py +310 -0
- agentic_auth/services/enrollment_rules.py +80 -0
- agentic_auth/services/manifest_service.py +166 -0
- agentic_auth/services/metrics.py +419 -0
- agentic_auth/services/pdp.py +312 -0
- agentic_auth/services/policy_loader.py +255 -0
- agentic_auth/services/principal.py +143 -0
- agentic_auth/services/reconciler.py +119 -0
- agentic_auth/services/revocation.py +149 -0
- agentic_auth/services/sessions.py +231 -0
- agentic_auth/services/taint.py +204 -0
- agentic_auth/services/tokens/__init__.py +11 -0
- agentic_auth/services/tokens/act_chain.py +76 -0
- agentic_auth/services/tokens/exchange.py +319 -0
- agentic_auth/services/tokens/jwt_profile.py +362 -0
- agentic_auth/services/tokens/keys.py +117 -0
- agentic_auth/services/tokens/profile.py +167 -0
- agentic_auth/services/tokens/replay.py +53 -0
- agentic_auth/services/transactions.py +172 -0
- agentic_auth/sidecar/__init__.py +7 -0
- agentic_auth/sidecar/__main__.py +66 -0
- agentic_auth/sidecar/app.py +349 -0
- agentic_auth/sidecar/config.py +253 -0
- agentic_auth/sidecar/deny.py +108 -0
- agentic_auth/sidecar/enforce.py +640 -0
- agentic_auth/sidecar/identity.py +37 -0
- agentic_auth/verify/__init__.py +208 -0
- agentic_auth/verify/admit.py +131 -0
- agentic_auth/verify/anchors.py +250 -0
- agentic_auth/verify/canonical.py +228 -0
- agentic_auth/verify/grants.py +158 -0
- agentic_auth/verify/identity.py +111 -0
- agentic_auth/verify/replay.py +67 -0
- agentic_auth/verify/transaction.py +164 -0
- authzai-0.2.0.dist-info/METADATA +276 -0
- authzai-0.2.0.dist-info/RECORD +148 -0
- authzai-0.2.0.dist-info/WHEEL +5 -0
- authzai-0.2.0.dist-info/entry_points.txt +5 -0
- authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
- authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
- authzai-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""The observability layer's public surface.
|
|
2
|
+
|
|
3
|
+
Four functions, and every one of them is safe to call when telemetry is off, when the
|
|
4
|
+
OpenTelemetry SDK is not installed, and when the collector is unreachable:
|
|
5
|
+
|
|
6
|
+
setup(...) -> configure this process. Idempotent. Never raises.
|
|
7
|
+
tracer() -> a tracer; a no-op tracer when disabled.
|
|
8
|
+
config() -> the resolved ObservabilityConfig, for attribute builders and /status.
|
|
9
|
+
shutdown() -> flush and stop. Called at process exit, never on a request path.
|
|
10
|
+
|
|
11
|
+
**Fail-open, by construction**. Telemetry is the opposite posture to audit:
|
|
12
|
+
``api/v1/authorize.py`` refuses to return an allow for a decision it could not record, while a
|
|
13
|
+
dead collector here changes nothing. Any exception during setup disables telemetry and leaves the
|
|
14
|
+
component running — a guardrail that refused to start because a collector was down would be an
|
|
15
|
+
availability regression caused by an observability feature.
|
|
16
|
+
|
|
17
|
+
**This module never calls ``set_tracer_provider()`` for a process it does not own.** That
|
|
18
|
+
function is process-global and warns-and-ignores on a second call, so a library that calls it
|
|
19
|
+
either hijacks the host's pipeline or silently emits nothing. The control plane and the sidecar
|
|
20
|
+
own their processes and opt in explicitly via ``install_globally=True``; the verifier library
|
|
21
|
+
never does.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import logging
|
|
28
|
+
from typing import TYPE_CHECKING, Any
|
|
29
|
+
|
|
30
|
+
from agentic_auth.observability.config import (
|
|
31
|
+
DISABLED,
|
|
32
|
+
ObservabilityConfig,
|
|
33
|
+
from_settings,
|
|
34
|
+
sdk_available,
|
|
35
|
+
)
|
|
36
|
+
from agentic_auth.observability.context import extract_parent, inject
|
|
37
|
+
from agentic_auth.observability.spans import (
|
|
38
|
+
decision_attributes,
|
|
39
|
+
exchange_attributes,
|
|
40
|
+
mint_attributes,
|
|
41
|
+
pep_attributes,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
if TYPE_CHECKING: # pragma: no cover - typing only
|
|
45
|
+
from opentelemetry.trace import Tracer
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"ObservabilityConfig",
|
|
51
|
+
"OtelSink",
|
|
52
|
+
"config",
|
|
53
|
+
"decision_attributes",
|
|
54
|
+
"exchange_attributes",
|
|
55
|
+
"extract_parent",
|
|
56
|
+
"inject",
|
|
57
|
+
"mint_attributes",
|
|
58
|
+
"pep_attributes",
|
|
59
|
+
"setup",
|
|
60
|
+
"shutdown",
|
|
61
|
+
"tracer",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
INSTRUMENTATION_SCOPE = "agentic-auth"
|
|
65
|
+
|
|
66
|
+
_config: ObservabilityConfig = DISABLED
|
|
67
|
+
_provider: Any = None
|
|
68
|
+
_logging_handler: Any = None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def config() -> ObservabilityConfig:
|
|
72
|
+
return _config
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def setup(
|
|
76
|
+
*,
|
|
77
|
+
service_name: str = "control_plane",
|
|
78
|
+
resolved: ObservabilityConfig | None = None,
|
|
79
|
+
install_globally: bool = True,
|
|
80
|
+
metrics: Any = None,
|
|
81
|
+
exporter: Any = None,
|
|
82
|
+
synchronous_export: bool = False,
|
|
83
|
+
) -> ObservabilityConfig:
|
|
84
|
+
"""Configure telemetry for this process. Idempotent, and never raises.
|
|
85
|
+
|
|
86
|
+
``resolved`` lets the sidecar pass its own configuration instead of the control plane's
|
|
87
|
+
settings. ``metrics`` is a registry whose ``telemetry_dropped`` counter the export pipeline
|
|
88
|
+
feeds, so telemetry loss reports itself. ``exporter`` overrides the OTLP exporter —
|
|
89
|
+
the tests pass an in-memory one, and the fault-injection suite passes a failing one.
|
|
90
|
+
``synchronous_export`` swaps the batching processor for a simple one, so a test sees a span
|
|
91
|
+
the moment it ends instead of having to flush.
|
|
92
|
+
"""
|
|
93
|
+
global _config, _provider, _logging_handler
|
|
94
|
+
|
|
95
|
+
if _provider is not None:
|
|
96
|
+
return _config
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
_config = resolved if resolved is not None else from_settings(service_name)
|
|
100
|
+
except Exception:
|
|
101
|
+
logger.warning("could not resolve telemetry configuration; telemetry is off")
|
|
102
|
+
_config = DISABLED
|
|
103
|
+
return _config
|
|
104
|
+
|
|
105
|
+
_config.log_state_once()
|
|
106
|
+
if not _config.enabled:
|
|
107
|
+
return _config
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
_provider, _logging_handler = _build_pipeline(
|
|
111
|
+
_config, install_globally, metrics, exporter, synchronous_export
|
|
112
|
+
)
|
|
113
|
+
except Exception:
|
|
114
|
+
# Deliberately broad. Any failure here — a missing exporter extra, a malformed
|
|
115
|
+
# endpoint, a provider that cannot start — must leave the process serving.
|
|
116
|
+
logger.warning("telemetry setup failed; continuing without it", exc_info=False)
|
|
117
|
+
_config = ObservabilityConfig(
|
|
118
|
+
enabled=False,
|
|
119
|
+
key=_config.key,
|
|
120
|
+
identity_disclosure=False,
|
|
121
|
+
allow_sample_ratio=_config.allow_sample_ratio,
|
|
122
|
+
service_name=_config.service_name,
|
|
123
|
+
state="setup_failed",
|
|
124
|
+
)
|
|
125
|
+
_provider = None
|
|
126
|
+
return _config
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _build_pipeline(
|
|
130
|
+
cfg: ObservabilityConfig,
|
|
131
|
+
install_globally: bool,
|
|
132
|
+
metrics: Any,
|
|
133
|
+
exporter: Any = None,
|
|
134
|
+
synchronous_export: bool = False,
|
|
135
|
+
) -> tuple[Any, Any]:
|
|
136
|
+
"""Build the tracer provider and the logging bridge. Imported lazily: these are the optional
|
|
137
|
+
``otel`` extra, and nothing above may import them at module scope."""
|
|
138
|
+
from opentelemetry import trace as trace_api
|
|
139
|
+
from opentelemetry.sdk.resources import Resource
|
|
140
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
141
|
+
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor
|
|
142
|
+
|
|
143
|
+
from agentic_auth.observability.tracing import AlwaysSampleAuthz, RefusalPreservingFilter
|
|
144
|
+
|
|
145
|
+
resource = Resource.create({"service.name": f"agentic-auth-{cfg.service_name}"})
|
|
146
|
+
provider = TracerProvider(sampler=AlwaysSampleAuthz(), resource=resource)
|
|
147
|
+
|
|
148
|
+
exporter = exporter if exporter is not None else _span_exporter()
|
|
149
|
+
if exporter is not None:
|
|
150
|
+
# BatchSpanProcessor is the bounded queue and the background export thread. Giving it a
|
|
151
|
+
# meter_provider is what makes its own dropped/queued counts observable, rather than us
|
|
152
|
+
# counting them by hand.
|
|
153
|
+
batch = (
|
|
154
|
+
SimpleSpanProcessor(exporter)
|
|
155
|
+
if synchronous_export
|
|
156
|
+
else BatchSpanProcessor(exporter, meter_provider=_meter_provider(metrics))
|
|
157
|
+
)
|
|
158
|
+
provider.add_span_processor(
|
|
159
|
+
RefusalPreservingFilter(
|
|
160
|
+
batch,
|
|
161
|
+
allow_sample_ratio=cfg.allow_sample_ratio,
|
|
162
|
+
on_drop=_drop_recorder(metrics),
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
if install_globally:
|
|
167
|
+
trace_api.set_tracer_provider(provider)
|
|
168
|
+
|
|
169
|
+
return provider, _install_log_bridge(cfg)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _drop_recorder(metrics: Any) -> Any:
|
|
173
|
+
"""Feed ``agentic_auth_telemetry_dropped`` from the sampling filter.
|
|
174
|
+
|
|
175
|
+
Sampling drops and queue-overflow drops are both telemetry loss, and the design requires the
|
|
176
|
+
loss to report itself. ``None`` when there is no registry to write to.
|
|
177
|
+
"""
|
|
178
|
+
if metrics is None:
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
def _record() -> None:
|
|
182
|
+
with contextlib.suppress(Exception): # pragma: no cover - never fatal
|
|
183
|
+
metrics.telemetry_dropped.labels(signal="span").inc()
|
|
184
|
+
|
|
185
|
+
return _record
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _span_exporter() -> Any:
|
|
189
|
+
"""The OTLP/HTTP span exporter, or ``None`` when no endpoint is configured.
|
|
190
|
+
|
|
191
|
+
Endpoint, headers, timeout and protocol all come from the standard ``OTEL_EXPORTER_OTLP_*``
|
|
192
|
+
variables, read by the exporter itself. We define no names of our own, which is what makes
|
|
193
|
+
the "configuration only" promise true for an integrator who already sets them.
|
|
194
|
+
"""
|
|
195
|
+
import os
|
|
196
|
+
|
|
197
|
+
if not (
|
|
198
|
+
os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
|
|
199
|
+
or os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
|
|
200
|
+
):
|
|
201
|
+
# No endpoint: traces are recorded in-process but not shipped. The local surfaces
|
|
202
|
+
# (/metrics, JSON logs on stdout) remain fully functional, and this is not an error.
|
|
203
|
+
return None
|
|
204
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
205
|
+
|
|
206
|
+
return OTLPSpanExporter()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _meter_provider(metrics: Any) -> Any:
|
|
210
|
+
"""BatchSpanProcessor's self-instrumentation target.
|
|
211
|
+
|
|
212
|
+
``None`` means the SDK uses the global meter provider, which is a no-op unless the integrator
|
|
213
|
+
configured one. We do not install an OTel meter provider: metrics stay on
|
|
214
|
+
``prometheus-client``, and ``agentic_auth_telemetry_dropped`` is incremented
|
|
215
|
+
from the drop path instead.
|
|
216
|
+
"""
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _install_log_bridge(cfg: ObservabilityConfig) -> Any:
|
|
221
|
+
"""Attach OTel's ``LoggingHandler`` to the root logger when an endpoint is configured.
|
|
222
|
+
|
|
223
|
+
The handler exports every non-reserved ``LogRecord`` attribute, so ``extra=`` arrives as
|
|
224
|
+
structured attributes with no adapter, and it attaches ``trace_id``/``span_id`` from the
|
|
225
|
+
active context automatically.
|
|
226
|
+
"""
|
|
227
|
+
import os
|
|
228
|
+
|
|
229
|
+
if not (
|
|
230
|
+
os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
|
|
231
|
+
or os.environ.get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT")
|
|
232
|
+
):
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
|
236
|
+
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
|
237
|
+
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
|
238
|
+
from opentelemetry.sdk.resources import Resource
|
|
239
|
+
|
|
240
|
+
provider = LoggerProvider(
|
|
241
|
+
resource=Resource.create({"service.name": f"agentic-auth-{cfg.service_name}"})
|
|
242
|
+
)
|
|
243
|
+
provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter()))
|
|
244
|
+
handler = LoggingHandler(logger_provider=provider)
|
|
245
|
+
logging.getLogger().addHandler(handler)
|
|
246
|
+
return handler
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class _NoOpSpan:
|
|
250
|
+
"""A span that does nothing, implemented without OpenTelemetry.
|
|
251
|
+
|
|
252
|
+
OTel's own ``NoOpTracer`` would be the obvious choice, but importing it requires the
|
|
253
|
+
optional extra — the very thing that may be missing. So call sites can use
|
|
254
|
+
``with tracer().start_as_current_span(...)`` unconditionally, in every configuration,
|
|
255
|
+
including a deployment that never installed the extra.
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
__slots__ = ()
|
|
259
|
+
|
|
260
|
+
def set_attribute(self, key: str, value: Any) -> None:
|
|
261
|
+
pass
|
|
262
|
+
|
|
263
|
+
def set_attributes(self, attributes: Any) -> None:
|
|
264
|
+
pass
|
|
265
|
+
|
|
266
|
+
def set_status(self, *args: Any, **kwargs: Any) -> None:
|
|
267
|
+
pass
|
|
268
|
+
|
|
269
|
+
def add_event(self, *args: Any, **kwargs: Any) -> None:
|
|
270
|
+
pass
|
|
271
|
+
|
|
272
|
+
def record_exception(self, *args: Any, **kwargs: Any) -> None:
|
|
273
|
+
pass
|
|
274
|
+
|
|
275
|
+
def update_name(self, name: str) -> None:
|
|
276
|
+
pass
|
|
277
|
+
|
|
278
|
+
def is_recording(self) -> bool:
|
|
279
|
+
return False
|
|
280
|
+
|
|
281
|
+
def end(self, end_time: int | None = None) -> None:
|
|
282
|
+
pass
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class _NoOpTracer:
|
|
286
|
+
"""Mirrors the slice of the OTel ``Tracer`` protocol this layer uses."""
|
|
287
|
+
|
|
288
|
+
__slots__ = ()
|
|
289
|
+
|
|
290
|
+
@contextlib.contextmanager
|
|
291
|
+
def start_as_current_span(self, name: str, *args: Any, **kwargs: Any) -> Any:
|
|
292
|
+
yield _NoOpSpan()
|
|
293
|
+
|
|
294
|
+
def start_span(self, name: str, *args: Any, **kwargs: Any) -> _NoOpSpan:
|
|
295
|
+
return _NoOpSpan()
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
_NO_OP_TRACER = _NoOpTracer()
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def tracer() -> Tracer:
|
|
302
|
+
"""A tracer for this layer's spans. A no-op when telemetry is off, so call sites need no
|
|
303
|
+
conditionals — ``with tracer().start_as_current_span(...)`` is always valid."""
|
|
304
|
+
if _provider is not None:
|
|
305
|
+
return _provider.get_tracer(INSTRUMENTATION_SCOPE)
|
|
306
|
+
return _NO_OP_TRACER # type: ignore[return-value]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class OtelSink:
|
|
310
|
+
"""An OTel-backed :class:`agentic_auth.verify.TelemetrySink`, constructed by the integrator.
|
|
311
|
+
|
|
312
|
+
Lives here rather than in ``agentic_auth/verify/`` because the verifier must stay importable
|
|
313
|
+
with only ``pyjwt[crypto]``. The provider is passed in, never discovered and
|
|
314
|
+
never installed: ``set_tracer_provider`` is process-global, so a library that calls it in a
|
|
315
|
+
host it does not own either hijacks the host's pipeline or silently emits nothing.
|
|
316
|
+
|
|
317
|
+
from opentelemetry import trace
|
|
318
|
+
from agentic_auth.observability import OtelSink
|
|
319
|
+
from agentic_auth.verify import Verifier
|
|
320
|
+
|
|
321
|
+
verifier = Verifier(..., telemetry=OtelSink(trace.get_tracer_provider()))
|
|
322
|
+
|
|
323
|
+
Attributes are passed through as given: the verifier runs in the integrator's process, so
|
|
324
|
+
it is their disclosure policy that applies, not ours.
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
__slots__ = ("_tracer",)
|
|
328
|
+
|
|
329
|
+
def __init__(self, tracer_provider: Any, scope: str = INSTRUMENTATION_SCOPE) -> None:
|
|
330
|
+
self._tracer = tracer_provider.get_tracer(scope)
|
|
331
|
+
|
|
332
|
+
def span(self, name: str, attributes: Any) -> None:
|
|
333
|
+
clean = {k: v for k, v in dict(attributes).items() if v is not None}
|
|
334
|
+
with self._tracer.start_as_current_span(name, attributes=clean, record_exception=False):
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
def event(self, name: str, attributes: Any) -> None:
|
|
338
|
+
from opentelemetry import trace as trace_api
|
|
339
|
+
|
|
340
|
+
clean = {k: v for k, v in dict(attributes).items() if v is not None}
|
|
341
|
+
trace_api.get_current_span().add_event(name, attributes=clean)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def shutdown(timeout_millis: int = 5000) -> None:
|
|
345
|
+
"""Flush and stop. Called at process exit only.
|
|
346
|
+
|
|
347
|
+
``force_flush`` is the one place telemetry can block, which is why it is never called on a
|
|
348
|
+
request path.
|
|
349
|
+
"""
|
|
350
|
+
global _provider, _logging_handler
|
|
351
|
+
provider, _provider = _provider, None
|
|
352
|
+
handler, _logging_handler = _logging_handler, None
|
|
353
|
+
|
|
354
|
+
if handler is not None:
|
|
355
|
+
with contextlib.suppress(Exception): # pragma: no cover - defensive
|
|
356
|
+
logging.getLogger().removeHandler(handler)
|
|
357
|
+
if provider is not None:
|
|
358
|
+
try:
|
|
359
|
+
provider.force_flush(timeout_millis)
|
|
360
|
+
provider.shutdown()
|
|
361
|
+
except Exception: # pragma: no cover - defensive
|
|
362
|
+
logger.debug("telemetry shutdown failed", exc_info=False)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _reset_for_tests() -> None:
|
|
366
|
+
"""Tear down module state between tests. Not part of the public surface."""
|
|
367
|
+
global _config
|
|
368
|
+
shutdown(timeout_millis=100)
|
|
369
|
+
_config = DISABLED
|
|
370
|
+
sdk_available.cache_clear()
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Configuration and the no-op fallback for the observability layer.
|
|
2
|
+
|
|
3
|
+
Three independent reasons the layer stays silent, and all three must be checked before anything
|
|
4
|
+
is exported:
|
|
5
|
+
|
|
6
|
+
1. ``telemetry_enabled`` is false — the default, so a Phase 1-5 deployment is unchanged.
|
|
7
|
+
2. The OpenTelemetry SDK is not installed. It is an optional extra (``pip install '.[otel]'``),
|
|
8
|
+
imported lazily and never at module import time, so the control plane and the sidecar both
|
|
9
|
+
start and serve without it.
|
|
10
|
+
3. ``telemetry_key`` is empty. This one is a *refusal*, not an absence: the key is what makes
|
|
11
|
+
identity pseudonyms non-reversible, and exporting without it would mean either plaintext
|
|
12
|
+
identities or an unkeyed digest that is recovered by brute force. We log once and export
|
|
13
|
+
nothing rather than guess.
|
|
14
|
+
|
|
15
|
+
In all three cases the component keeps serving traffic. A guardrail that refused to start
|
|
16
|
+
because a collector was unreachable would be an availability regression caused by an
|
|
17
|
+
observability feature.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import logging
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from functools import lru_cache
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
# Why the layer is silent, for the one-time startup log and for GET /__agentic/status.
|
|
29
|
+
DISABLED_BY_SETTING = "disabled"
|
|
30
|
+
DISABLED_SDK_MISSING = "sdk_missing"
|
|
31
|
+
DISABLED_NO_KEY = "no_key"
|
|
32
|
+
ENABLED = "enabled"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@lru_cache(maxsize=1)
|
|
36
|
+
def sdk_available() -> bool:
|
|
37
|
+
"""Is the OpenTelemetry SDK importable? Cached, because the answer cannot change within a
|
|
38
|
+
process and the import attempt is not free."""
|
|
39
|
+
try:
|
|
40
|
+
import opentelemetry.sdk.trace # noqa: F401
|
|
41
|
+
except ImportError:
|
|
42
|
+
return False
|
|
43
|
+
return True
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class ObservabilityConfig:
|
|
48
|
+
"""Resolved telemetry configuration for one process."""
|
|
49
|
+
|
|
50
|
+
enabled: bool
|
|
51
|
+
key: bytes
|
|
52
|
+
identity_disclosure: bool
|
|
53
|
+
allow_sample_ratio: float
|
|
54
|
+
service_name: str
|
|
55
|
+
state: str
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def resolve(
|
|
59
|
+
cls,
|
|
60
|
+
*,
|
|
61
|
+
enabled: bool,
|
|
62
|
+
key: str,
|
|
63
|
+
identity_disclosure: bool,
|
|
64
|
+
allow_sample_ratio: float,
|
|
65
|
+
service_name: str,
|
|
66
|
+
) -> ObservabilityConfig:
|
|
67
|
+
"""Apply the three silencing rules above, in order, and report which one fired."""
|
|
68
|
+
state = ENABLED
|
|
69
|
+
if not enabled:
|
|
70
|
+
state = DISABLED_BY_SETTING
|
|
71
|
+
elif not sdk_available():
|
|
72
|
+
state = DISABLED_SDK_MISSING
|
|
73
|
+
elif not key:
|
|
74
|
+
state = DISABLED_NO_KEY
|
|
75
|
+
|
|
76
|
+
# Clamped rather than rejected: a nonsensical ratio should not stop a process from
|
|
77
|
+
# starting, and both ends of the clamp are safe (1.0 keeps everything; 0.0 keeps every
|
|
78
|
+
# refusal regardless, because refusals never consult this number).
|
|
79
|
+
ratio = min(1.0, max(0.0, allow_sample_ratio))
|
|
80
|
+
|
|
81
|
+
return cls(
|
|
82
|
+
enabled=state == ENABLED,
|
|
83
|
+
key=key.encode("utf-8"),
|
|
84
|
+
identity_disclosure=identity_disclosure and state == ENABLED,
|
|
85
|
+
allow_sample_ratio=ratio,
|
|
86
|
+
service_name=service_name,
|
|
87
|
+
state=state,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def log_state_once(self) -> None:
|
|
91
|
+
"""One line at startup saying what the layer is doing. Only the missing-key case is a
|
|
92
|
+
warning: the other two are deliberate configurations, not faults."""
|
|
93
|
+
if self.state == DISABLED_NO_KEY:
|
|
94
|
+
logger.warning(
|
|
95
|
+
"telemetry is enabled but AGENTIC_AUTH_TELEMETRY_KEY is empty; "
|
|
96
|
+
"exporting nothing rather than exporting identities in the clear",
|
|
97
|
+
extra={"authz.component": self.service_name},
|
|
98
|
+
)
|
|
99
|
+
elif self.state == DISABLED_SDK_MISSING:
|
|
100
|
+
logger.info(
|
|
101
|
+
"telemetry is enabled but the OpenTelemetry SDK is not installed; "
|
|
102
|
+
"install the 'otel' extra to export traces and logs",
|
|
103
|
+
extra={"authz.component": self.service_name},
|
|
104
|
+
)
|
|
105
|
+
elif self.state == ENABLED:
|
|
106
|
+
logger.info(
|
|
107
|
+
"telemetry enabled",
|
|
108
|
+
extra={
|
|
109
|
+
"authz.component": self.service_name,
|
|
110
|
+
"authz.identity_disclosure": self.identity_disclosure,
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def from_settings(service_name: str = "control_plane") -> ObservabilityConfig:
|
|
116
|
+
"""Resolve from ``agentic_auth.config.Settings``. Imported here rather than at module scope so
|
|
117
|
+
the sidecar, which has its own configuration, does not pull the control plane's settings in."""
|
|
118
|
+
from agentic_auth.config import get_settings
|
|
119
|
+
|
|
120
|
+
s = get_settings()
|
|
121
|
+
return ObservabilityConfig.resolve(
|
|
122
|
+
enabled=s.telemetry_enabled,
|
|
123
|
+
key=s.telemetry_key,
|
|
124
|
+
identity_disclosure=s.telemetry_identity_disclosure,
|
|
125
|
+
allow_sample_ratio=s.telemetry_allow_sample_ratio,
|
|
126
|
+
service_name=service_name,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
DISABLED = ObservabilityConfig(
|
|
131
|
+
enabled=False,
|
|
132
|
+
key=b"",
|
|
133
|
+
identity_disclosure=False,
|
|
134
|
+
allow_sample_ratio=1.0,
|
|
135
|
+
service_name="unconfigured",
|
|
136
|
+
state=DISABLED_BY_SETTING,
|
|
137
|
+
)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Inbound trace context, treated as untrusted input.
|
|
2
|
+
|
|
3
|
+
A caller-supplied ``traceparent`` arrives from an agent process we may not control. Three rules,
|
|
4
|
+
all enforced here so no call site has to remember them:
|
|
5
|
+
|
|
6
|
+
1. **`tracecontext` only.** The SDK default is ``tracecontext,baggage``, and
|
|
7
|
+
``W3CBaggagePropagator`` would extract arbitrary attacker-controlled key/value data on the way
|
|
8
|
+
in and **re-inject it into every outbound call**. An agent could use it to smuggle unbounded
|
|
9
|
+
content through our telemetry, or to spoof fields a backend treats as trustworthy. We
|
|
10
|
+
instantiate the trace-context propagator directly rather than reading ``OTEL_PROPAGATORS``, so
|
|
11
|
+
an integrator who enables baggage for their own services cannot enable it on ours.
|
|
12
|
+
2. **`tracestate` is discarded.** Neither read nor propagated.
|
|
13
|
+
3. **Nothing inbound reaches a decision.** No value here is read by the authorization path, and
|
|
14
|
+
none is written to an audit row, a deny reason, or a metric label.
|
|
15
|
+
|
|
16
|
+
What a caller *can* do is claim any trace id, and so make its spans appear inside another trace.
|
|
17
|
+
That is a correlation nuisance, not a security bypass, and it has one consequence worth stating
|
|
18
|
+
plainly:
|
|
19
|
+
|
|
20
|
+
**A trace id is never evidence.** The audit record, keyed by ``action_id``, is the evidence.
|
|
21
|
+
The span is a handle that points at it.
|
|
22
|
+
|
|
23
|
+
``traceparent`` is fixed-length by the W3C format, so with baggage and tracestate dropped there
|
|
24
|
+
is no unbounded-input vector left.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import logging
|
|
30
|
+
from functools import lru_cache
|
|
31
|
+
from typing import TYPE_CHECKING, Any
|
|
32
|
+
|
|
33
|
+
from agentic_auth.observability.ids import session_parent_context
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING: # pragma: no cover - typing only
|
|
36
|
+
from collections.abc import Mapping
|
|
37
|
+
|
|
38
|
+
from opentelemetry.context import Context
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
TRACEPARENT = "traceparent"
|
|
43
|
+
|
|
44
|
+
# Reject causes, matching surface.TRACE_CONTEXT_REJECT_CAUSES.
|
|
45
|
+
CAUSE_MALFORMED = "malformed"
|
|
46
|
+
CAUSE_ABSENT = "absent"
|
|
47
|
+
CAUSE_BAGGAGE_DROPPED = "baggage_dropped"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@lru_cache(maxsize=1)
|
|
51
|
+
def _propagator() -> Any:
|
|
52
|
+
"""Deliberately not the global propagator — see rule 1 above — and deliberately built
|
|
53
|
+
lazily: the OpenTelemetry API is an optional extra, so nothing in this package may import
|
|
54
|
+
it at module scope. The gate (the suite passing with the extra uninstalled) is what
|
|
55
|
+
enforces that."""
|
|
56
|
+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
|
57
|
+
|
|
58
|
+
return TraceContextTextMapPropagator()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# Headers a caller may send that we refuse to honour or forward.
|
|
62
|
+
_REFUSED_HEADERS = ("baggage", "tracestate")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _record(metrics: object | None, cause: str) -> None:
|
|
66
|
+
"""Count a rejection, if a registry was supplied. Never raises: a missing or half-built
|
|
67
|
+
metrics object must not break a request."""
|
|
68
|
+
if metrics is None:
|
|
69
|
+
return
|
|
70
|
+
try:
|
|
71
|
+
metrics.trace_context_rejected.labels(cause=cause).inc() # type: ignore[attr-defined]
|
|
72
|
+
except Exception: # pragma: no cover - defensive
|
|
73
|
+
logger.debug("could not record a trace-context rejection", exc_info=False)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def extract_parent(
|
|
77
|
+
headers: Mapping[str, str],
|
|
78
|
+
*,
|
|
79
|
+
session_id: str | None,
|
|
80
|
+
key: bytes,
|
|
81
|
+
metrics: object | None = None,
|
|
82
|
+
) -> Context | None:
|
|
83
|
+
"""Resolve the parent context for a span, from the caller's headers or from the session.
|
|
84
|
+
|
|
85
|
+
Returns ``None`` when there is neither usable inbound context nor a session id, which leaves
|
|
86
|
+
the SDK to start a fresh random root — correct for a call that belongs to no session.
|
|
87
|
+
|
|
88
|
+
``propagate.extract`` returns a context with no valid span context when ``traceparent`` is
|
|
89
|
+
malformed, rather than raising, so the fallback would be silent. We detect it deliberately
|
|
90
|
+
and count it: a deployment cannot otherwise tell cooperative callers from broken ones.
|
|
91
|
+
"""
|
|
92
|
+
# Rule 1/2: note and drop anything we refuse to honour, before looking at traceparent, so
|
|
93
|
+
# the drop is counted even when the caller also sent a perfectly good traceparent.
|
|
94
|
+
for refused in _REFUSED_HEADERS:
|
|
95
|
+
if refused in headers or refused.title() in headers:
|
|
96
|
+
_record(metrics, CAUSE_BAGGAGE_DROPPED)
|
|
97
|
+
break
|
|
98
|
+
|
|
99
|
+
raw = headers.get(TRACEPARENT) or headers.get("Traceparent")
|
|
100
|
+
if raw:
|
|
101
|
+
# Only traceparent is passed to the propagator. tracestate is not forwarded even though
|
|
102
|
+
# the W3C propagator would accept it, so a caller cannot seed vendor state.
|
|
103
|
+
from opentelemetry import trace as trace_api
|
|
104
|
+
|
|
105
|
+
context = _propagator().extract({TRACEPARENT: raw})
|
|
106
|
+
span_context = trace_api.get_current_span(context).get_span_context()
|
|
107
|
+
if span_context.is_valid:
|
|
108
|
+
return context
|
|
109
|
+
_record(metrics, CAUSE_MALFORMED)
|
|
110
|
+
else:
|
|
111
|
+
_record(metrics, CAUSE_ABSENT)
|
|
112
|
+
|
|
113
|
+
if session_id and key:
|
|
114
|
+
# One chain, one trace, with no cooperation from the caller and no channel between the
|
|
115
|
+
# control plane and the PEP.
|
|
116
|
+
return session_parent_context(session_id, key)
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def inject(headers: dict[str, str]) -> dict[str, str]:
|
|
121
|
+
"""Add ``traceparent`` for an outbound call the SDK controls.
|
|
122
|
+
|
|
123
|
+
Only trace context goes out — no baggage, no tracestate. The sidecar's **upstream** leg needs
|
|
124
|
+
no help: ``traceparent`` is not a hop-by-hop header and is deliberately absent from
|
|
125
|
+
``_SKIP_REQUEST_HEADERS`` in ``agentic_auth/sidecar/app.py``, so it already passes through.
|
|
126
|
+
"""
|
|
127
|
+
_propagator().inject(headers)
|
|
128
|
+
return headers
|