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.
Files changed (148) hide show
  1. agentic_auth/__init__.py +8 -0
  2. agentic_auth/_extras.py +24 -0
  3. agentic_auth/api/__init__.py +0 -0
  4. agentic_auth/api/deps.py +112 -0
  5. agentic_auth/api/errors.py +51 -0
  6. agentic_auth/api/responses.py +38 -0
  7. agentic_auth/api/service_deps.py +113 -0
  8. agentic_auth/api/v1/__init__.py +0 -0
  9. agentic_auth/api/v1/agents.py +88 -0
  10. agentic_auth/api/v1/audit.py +67 -0
  11. agentic_auth/api/v1/authorize.py +439 -0
  12. agentic_auth/api/v1/consent.py +21 -0
  13. agentic_auth/api/v1/decisions.py +43 -0
  14. agentic_auth/api/v1/enrollment.py +48 -0
  15. agentic_auth/api/v1/identity.py +97 -0
  16. agentic_auth/api/v1/jwks.py +21 -0
  17. agentic_auth/api/v1/manifests.py +68 -0
  18. agentic_auth/api/v1/scopes.py +22 -0
  19. agentic_auth/api/v1/token.py +203 -0
  20. agentic_auth/api/v1/transaction.py +94 -0
  21. agentic_auth/boundary/__init__.py +26 -0
  22. agentic_auth/boundary/guarantee.py +96 -0
  23. agentic_auth/cli/__init__.py +27 -0
  24. agentic_auth/cli/audit.py +130 -0
  25. agentic_auth/cli/drift.py +164 -0
  26. agentic_auth/cli/drift_render.py +148 -0
  27. agentic_auth/cli/identity.py +63 -0
  28. agentic_auth/cli/manifest.py +275 -0
  29. agentic_auth/config.py +182 -0
  30. agentic_auth/db.py +49 -0
  31. agentic_auth/embedded/__init__.py +427 -0
  32. agentic_auth/embedded/_schema.py +8 -0
  33. agentic_auth/embedded/_transport.py +39 -0
  34. agentic_auth/embedded/capabilities.py +34 -0
  35. agentic_auth/embedded/export.py +86 -0
  36. agentic_auth/embedded/idp.py +78 -0
  37. agentic_auth/embedded/store.py +240 -0
  38. agentic_auth/errors.py +145 -0
  39. agentic_auth/main.py +141 -0
  40. agentic_auth/models/__init__.py +70 -0
  41. agentic_auth/models/agent.py +58 -0
  42. agentic_auth/models/audit_decision.py +199 -0
  43. agentic_auth/models/compiled_policy.py +28 -0
  44. agentic_auth/models/manifest.py +96 -0
  45. agentic_auth/models/reconciliation_report.py +27 -0
  46. agentic_auth/models/sandbox_run.py +93 -0
  47. agentic_auth/models/session.py +63 -0
  48. agentic_auth/models/step_up_grant.py +106 -0
  49. agentic_auth/models/transaction_token.py +73 -0
  50. agentic_auth/models/trust_anchor.py +59 -0
  51. agentic_auth/models/types.py +95 -0
  52. agentic_auth/observability/__init__.py +370 -0
  53. agentic_auth/observability/config.py +137 -0
  54. agentic_auth/observability/context.py +128 -0
  55. agentic_auth/observability/ids.py +122 -0
  56. agentic_auth/observability/logs.py +191 -0
  57. agentic_auth/observability/pep.py +169 -0
  58. agentic_auth/observability/spans.py +225 -0
  59. agentic_auth/observability/surface.py +286 -0
  60. agentic_auth/observability/tracing.py +167 -0
  61. agentic_auth/redis.py +27 -0
  62. agentic_auth/repositories/__init__.py +0 -0
  63. agentic_auth/repositories/agents.py +96 -0
  64. agentic_auth/repositories/audit_decisions.py +152 -0
  65. agentic_auth/repositories/compiled_policies.py +72 -0
  66. agentic_auth/repositories/manifests.py +149 -0
  67. agentic_auth/repositories/reconciliation_reports.py +40 -0
  68. agentic_auth/repositories/sessions.py +41 -0
  69. agentic_auth/repositories/transaction_tokens.py +60 -0
  70. agentic_auth/repositories/trust_anchors.py +150 -0
  71. agentic_auth/runtime.py +81 -0
  72. agentic_auth/schemas/__init__.py +0 -0
  73. agentic_auth/schemas/agent.py +58 -0
  74. agentic_auth/schemas/audit.py +207 -0
  75. agentic_auth/schemas/authorize.py +205 -0
  76. agentic_auth/schemas/common.py +40 -0
  77. agentic_auth/schemas/consent.py +74 -0
  78. agentic_auth/schemas/dag.py +39 -0
  79. agentic_auth/schemas/edge_trace.py +166 -0
  80. agentic_auth/schemas/identity.py +152 -0
  81. agentic_auth/schemas/manifest.py +117 -0
  82. agentic_auth/schemas/manifest_api.py +38 -0
  83. agentic_auth/schemas/reconciliation.py +49 -0
  84. agentic_auth/schemas/token.py +122 -0
  85. agentic_auth/schemas/transaction.py +28 -0
  86. agentic_auth/sdk/__init__.py +114 -0
  87. agentic_auth/sdk/client.py +677 -0
  88. agentic_auth/sdk/context.py +95 -0
  89. agentic_auth/sdk/drift.py +118 -0
  90. agentic_auth/sdk/errors.py +147 -0
  91. agentic_auth/sdk/identity.py +162 -0
  92. agentic_auth/sdk/planes.py +362 -0
  93. agentic_auth/sdk/provenance.py +63 -0
  94. agentic_auth/services/__init__.py +0 -0
  95. agentic_auth/services/anchors.py +81 -0
  96. agentic_auth/services/audit.py +222 -0
  97. agentic_auth/services/audit_chain.py +144 -0
  98. agentic_auth/services/audit_cursor.py +55 -0
  99. agentic_auth/services/catalog_service.py +58 -0
  100. agentic_auth/services/chain_query.py +152 -0
  101. agentic_auth/services/dag_compiler.py +199 -0
  102. agentic_auth/services/decision_cache.py +123 -0
  103. agentic_auth/services/decision_history.py +71 -0
  104. agentic_auth/services/discovery.py +95 -0
  105. agentic_auth/services/drift.py +330 -0
  106. agentic_auth/services/edge_rules.py +62 -0
  107. agentic_auth/services/edge_trace.py +198 -0
  108. agentic_auth/services/enrollment.py +310 -0
  109. agentic_auth/services/enrollment_rules.py +80 -0
  110. agentic_auth/services/manifest_service.py +166 -0
  111. agentic_auth/services/metrics.py +419 -0
  112. agentic_auth/services/pdp.py +312 -0
  113. agentic_auth/services/policy_loader.py +255 -0
  114. agentic_auth/services/principal.py +143 -0
  115. agentic_auth/services/reconciler.py +119 -0
  116. agentic_auth/services/revocation.py +149 -0
  117. agentic_auth/services/sessions.py +231 -0
  118. agentic_auth/services/taint.py +204 -0
  119. agentic_auth/services/tokens/__init__.py +11 -0
  120. agentic_auth/services/tokens/act_chain.py +76 -0
  121. agentic_auth/services/tokens/exchange.py +319 -0
  122. agentic_auth/services/tokens/jwt_profile.py +362 -0
  123. agentic_auth/services/tokens/keys.py +117 -0
  124. agentic_auth/services/tokens/profile.py +167 -0
  125. agentic_auth/services/tokens/replay.py +53 -0
  126. agentic_auth/services/transactions.py +172 -0
  127. agentic_auth/sidecar/__init__.py +7 -0
  128. agentic_auth/sidecar/__main__.py +66 -0
  129. agentic_auth/sidecar/app.py +349 -0
  130. agentic_auth/sidecar/config.py +253 -0
  131. agentic_auth/sidecar/deny.py +108 -0
  132. agentic_auth/sidecar/enforce.py +640 -0
  133. agentic_auth/sidecar/identity.py +37 -0
  134. agentic_auth/verify/__init__.py +208 -0
  135. agentic_auth/verify/admit.py +131 -0
  136. agentic_auth/verify/anchors.py +250 -0
  137. agentic_auth/verify/canonical.py +228 -0
  138. agentic_auth/verify/grants.py +158 -0
  139. agentic_auth/verify/identity.py +111 -0
  140. agentic_auth/verify/replay.py +67 -0
  141. agentic_auth/verify/transaction.py +164 -0
  142. authzai-0.2.0.dist-info/METADATA +276 -0
  143. authzai-0.2.0.dist-info/RECORD +148 -0
  144. authzai-0.2.0.dist-info/WHEEL +5 -0
  145. authzai-0.2.0.dist-info/entry_points.txt +5 -0
  146. authzai-0.2.0.dist-info/licenses/LICENSE +202 -0
  147. authzai-0.2.0.dist-info/licenses/NOTICE +8 -0
  148. authzai-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,122 @@
1
+ """Keyed identity pseudonyms and session-derived trace roots.
2
+
3
+ Two primitives, one secret (``AGENTIC_AUTH_TELEMETRY_KEY``):
4
+
5
+ - ``pseudonym()`` replaces an agent name or act chain in a trace or log with a stable,
6
+ non-reversible reference.
7
+ - ``session_trace_id()`` / ``session_parent_context()`` give every decision in one session the
8
+ same trace, even when no caller supplies a ``traceparent`` and even across processes that
9
+ share no context.
10
+
11
+ **Why the key, and not a plain hash.** Agent names are a small, enumerable space
12
+ (``agent://router``, ``agent://billing-writer``, ...). An unkeyed SHA-256 of one is recovered by
13
+ brute force in seconds by anyone holding the telemetry and a guess at the naming convention. A
14
+ MAC with a secret the telemetry backend does not hold defeats that. The same key makes a trace
15
+ id something other than a plaintext session handle in a third-party backend.
16
+
17
+ **Why no custom ``IdGenerator``**:
18
+ OTel's ``IdGenerator.generate_trace_id(self)`` takes no arguments, so a generator cannot see the
19
+ session id without process-global or contextvar state. Building a synthetic non-recording
20
+ *remote parent* from the derived id is deterministic per request, needs no global state, and
21
+ makes the trace id arrive from the parent context — so the SDK never generates one for these
22
+ spans and R4's ``is_trace_id_random`` caveat does not arise.
23
+
24
+ This module imports only the standard library plus the OTel **API** (not the SDK) for the
25
+ context helper, so the pure functions remain testable without the ``otel`` extra installed.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import hmac
32
+ from typing import TYPE_CHECKING
33
+
34
+ if TYPE_CHECKING: # pragma: no cover - typing only
35
+ from opentelemetry.context import Context
36
+
37
+ # 128 bits. Long enough that collisions are negligible at the design scale (1,000 agents x
38
+ # 100,000 sessions), short enough to keep span attributes readable.
39
+ PSEUDONYM_HEX_LEN = 32
40
+
41
+ _TRACE_ID_BYTES = 16
42
+ _SPAN_ID_BYTES = 8
43
+
44
+ # Domain prefixes. Separate namespaces so a target URI and an agent name with the same text
45
+ # never produce the same pseudonym.
46
+ KIND_AGENT = "agent"
47
+ KIND_CHAIN = "chain"
48
+ KIND_TARGET = "target"
49
+ KIND_SESSION = "session"
50
+ KIND_SPAN = "span"
51
+
52
+
53
+ def _frame(kind: str, value: str) -> str:
54
+ """Length-prefix the domain so the encoding is injective.
55
+
56
+ A bare ``f"{kind}:{value}"`` is ambiguous: ``("agent", "x:y")`` and ``("agent:x", "y")`` both
57
+ frame to ``"agent:x:y"``. Not exploitable while every ``kind`` is an internal constant, but an
58
+ encoding that *cannot* collide costs one integer and removes the need to reason about it.
59
+ """
60
+ return f"{len(kind)}:{kind}:{value}"
61
+
62
+
63
+ def _mac(key: bytes, label: str) -> bytes:
64
+ if not key:
65
+ # Reaching here means a caller bypassed ObservabilityConfig's refusal to enable without
66
+ # a key. Raising beats falling back to an unkeyed digest, which would look like it
67
+ # worked while being trivially reversible.
68
+ raise ValueError("a telemetry key is required; refusing to derive an unkeyed value")
69
+ return hmac.new(key, label.encode("utf-8"), hashlib.sha256).digest()
70
+
71
+
72
+ def pseudonym(kind: str, value: str, key: bytes) -> str:
73
+ """A stable, non-reversible reference to ``value`` within one deployment.
74
+
75
+ Stable: same key and input always give the same answer, in every process, forever — which is
76
+ what lets an operator group a deployment's telemetry by agent without learning which agent.
77
+ Non-reversible: not without the key.
78
+
79
+ Rotating the key re-pseudonymises everything and breaks historical grouping. That is the
80
+ documented cost of one secret serving both primitives here.
81
+ """
82
+ return _mac(key, _frame(kind, value)).hex()[:PSEUDONYM_HEX_LEN]
83
+
84
+
85
+ def session_trace_id(session_id: str, key: bytes) -> int:
86
+ """The 128-bit trace id every span in ``session_id`` belongs to, absent inbound context.
87
+
88
+ Derived, not generated, so two processes agree without a channel between them.
89
+ """
90
+ digest = _mac(key, _frame(KIND_SESSION, session_id))
91
+ trace_id = int.from_bytes(digest[:_TRACE_ID_BYTES], "big")
92
+ # 0 is INVALID_TRACE_ID and would be dropped by the SDK. Astronomically unlikely from a MAC,
93
+ # but a silent drop is a bad failure mode, so it is handled rather than assumed away.
94
+ return trace_id or 1
95
+
96
+
97
+ def session_root_span_id(session_id: str, key: bytes) -> int:
98
+ """The 64-bit id of the synthetic parent. Derived from its own domain rather than from the
99
+ trace id's low bytes, so neither leaks the other."""
100
+ digest = _mac(key, _frame(KIND_SPAN, session_id))
101
+ span_id = int.from_bytes(digest[:_SPAN_ID_BYTES], "big")
102
+ return span_id or 1
103
+
104
+
105
+ def session_parent_context(session_id: str, key: bytes) -> Context:
106
+ """A ``Context`` whose current span is a synthetic, non-recording remote parent for this
107
+ session.
108
+
109
+ Used as the parent when a caller sends no usable ``traceparent``. The parent itself is never
110
+ exported — it is a correlation handle, and ``is_remote=True`` says honestly that it did not
111
+ originate here. ``TraceFlags.SAMPLED`` is set because a child that inherited an unsampled
112
+ parent would be dropped, which must never happen to a refusal.
113
+ """
114
+ from opentelemetry import trace as trace_api
115
+
116
+ span_context = trace_api.SpanContext(
117
+ trace_id=session_trace_id(session_id, key),
118
+ span_id=session_root_span_id(session_id, key),
119
+ is_remote=True,
120
+ trace_flags=trace_api.TraceFlags(trace_api.TraceFlags.SAMPLED),
121
+ )
122
+ return trace_api.set_span_in_context(trace_api.NonRecordingSpan(span_context))
@@ -0,0 +1,191 @@
1
+ """Structured logs: a JSON formatter for stdout, and correlation fields via ``extra=``.
2
+
3
+ **No new logging library.** Two properties of OTel's ``LoggingHandler`` make the standard
4
+ library sufficient:
5
+
6
+ - It exports every non-reserved attribute of the ``LogRecord``, so ``extra={...}`` arrives at
7
+ the backend as structured attributes with no adapter in between.
8
+ - It builds the exported record with ``context=get_current()``, so ``trace_id`` and ``span_id``
9
+ are attached from the active span automatically — trace linkage needs no code at the
10
+ call sites.
11
+
12
+ It also maps Python levels to OTel severities (``WARNING``→``WARN``, ``CRITICAL``→``FATAL``),
13
+ which is what alerting needs: an expected policy deny at ``INFO`` and an unreachable control plane
14
+ at ``WARNING`` arrive distinguishable, with no custom mapping from us.
15
+
16
+ **What this module deliberately does not do** is record exceptions. ``logger.exception(...)``
17
+ sets ``exc_info``, and ``LoggingHandler`` then exports ``exception.message`` (as
18
+ ``str(value.args[0])``) and ``exception.stacktrace`` (the full formatted traceback). A traceback
19
+ through token verification can carry a token fragment, so dispatch-path call sites log
20
+ ``error.type`` and a static message instead. :func:`scrub_exception_fields` is the backstop that
21
+ strips those keys if one slips through.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import logging
28
+ from typing import Any
29
+
30
+ from agentic_auth.observability import surface
31
+
32
+ # Attributes the logging module puts on every record. Anything outside this set came from an
33
+ # `extra=`, which is what we want to export.
34
+ _RESERVED = frozenset(
35
+ {
36
+ "args",
37
+ "asctime",
38
+ "created",
39
+ "exc_info",
40
+ "exc_text",
41
+ "filename",
42
+ "funcName",
43
+ "levelname",
44
+ "levelno",
45
+ "lineno",
46
+ "module",
47
+ "msecs",
48
+ "message",
49
+ "msg",
50
+ "name",
51
+ "pathname",
52
+ "process",
53
+ "processName",
54
+ "relativeCreated",
55
+ "stack_info",
56
+ "taskName",
57
+ "thread",
58
+ "threadName",
59
+ }
60
+ )
61
+
62
+ # Never exported, even if something sets them. The SDK adds the first three itself when
63
+ # `exc_info` is present.
64
+ FORBIDDEN_LOG_FIELDS = frozenset(
65
+ {"exception.message", "exception.stacktrace", "exception.type", "exc_info", "exc_text"}
66
+ )
67
+
68
+
69
+ class JsonFormatter(logging.Formatter):
70
+ """One JSON object per line, with the correlation fields hoisted to the top level.
71
+
72
+ Used for stdout. When an OTLP sink is configured the same records also go through
73
+ ``LoggingHandler``, so a deployment with no collector still gets machine-parsable logs on
74
+ stdout — "the local surfaces remain fully functional".
75
+ """
76
+
77
+ def format(self, record: logging.LogRecord) -> str:
78
+ payload: dict[str, Any] = {
79
+ "severity": record.levelname,
80
+ "message": record.getMessage(),
81
+ "logger": record.name,
82
+ }
83
+ for key, value in vars(record).items():
84
+ if key in _RESERVED or key in FORBIDDEN_LOG_FIELDS or key.startswith("_"):
85
+ continue
86
+ payload[key] = value if _jsonable(value) else str(value)
87
+
88
+ span = _active_span_ids()
89
+ if span is not None:
90
+ payload["trace_id"], payload["span_id"] = span
91
+ return json.dumps(payload, default=str, sort_keys=True)
92
+
93
+
94
+ def _jsonable(value: Any) -> bool:
95
+ return isinstance(value, str | int | float | bool | type(None) | list | dict)
96
+
97
+
98
+ def _active_span_ids() -> tuple[str, str] | None:
99
+ """The active trace and span ids, or ``None``.
100
+
101
+ Imported lazily and failure-tolerantly: this must work in a process that never installed
102
+ the optional OpenTelemetry extra.
103
+ """
104
+ try:
105
+ from opentelemetry import trace as trace_api
106
+ except ImportError:
107
+ return None
108
+ try:
109
+ ctx = trace_api.get_current_span().get_span_context()
110
+ except Exception: # pragma: no cover - defensive
111
+ return None
112
+ if not ctx.is_valid:
113
+ return None
114
+ return format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
115
+
116
+
117
+ def fields(
118
+ component: str,
119
+ *,
120
+ session_id: Any = None,
121
+ action_id: Any = None,
122
+ hop: int | None = None,
123
+ error_type: str | None = None,
124
+ ) -> dict[str, Any]:
125
+ """Build the ``extra=`` mapping for a dispatch-path log record.
126
+
127
+ Only the fields in ``surface.LOG_FIELDS`` are produced, so a log record cannot acquire a
128
+ key the telemetry surface does not declare. Identifiers go here rather than into the
129
+ message, so the messages stay static and group.
130
+ """
131
+ out: dict[str, Any] = {surface.LOG_COMPONENT: component}
132
+ if session_id is not None:
133
+ out[surface.ATTR_SESSION_ID] = str(session_id)
134
+ if action_id is not None:
135
+ out[surface.ATTR_ACTION_ID] = str(action_id)
136
+ if hop is not None:
137
+ out[surface.ATTR_HOP] = hop
138
+ if error_type is not None:
139
+ out[surface.ATTR_ERROR_TYPE] = error_type
140
+ return out
141
+
142
+
143
+ def scrub_exception_fields(record: logging.LogRecord) -> logging.LogRecord:
144
+ """Drop ``exc_info`` so no stack trace is exported. The backstop for the no-secrets rule,
145
+ not the primary control — the primary control is that dispatch-path sites do not call
146
+ ``logger.exception`` at all."""
147
+ record.exc_info = None
148
+ record.exc_text = None
149
+ return record
150
+
151
+
152
+ class DispatchPathFilter(logging.Filter):
153
+ """Strips exception payloads from records emitted by the dispatch-path loggers.
154
+
155
+ Installed on the handlers rather than the loggers, so a library logger that happens to be
156
+ a child of one of these names is covered too.
157
+ """
158
+
159
+ LOGGERS = (
160
+ "agentic_auth.api.v1.authorize",
161
+ "agentic_auth.api.v1.token",
162
+ "agentic_auth.api.v1.transaction",
163
+ "agentic_auth.services.audit",
164
+ "agentic_auth.services.transactions",
165
+ "agentic_auth.sidecar.enforce",
166
+ "agentic_auth.sidecar.app",
167
+ )
168
+
169
+ def filter(self, record: logging.LogRecord) -> bool:
170
+ if record.exc_info and record.name.startswith(self.LOGGERS):
171
+ scrub_exception_fields(record)
172
+ return True
173
+
174
+
175
+ def configure(stream_handler: logging.Handler | None = None) -> logging.Handler:
176
+ """Install JSON formatting and the exception filter on the root logger.
177
+
178
+ Idempotent: calling it twice does not stack handlers, because a process that is configured
179
+ twice (an app factory invoked per test, say) should not emit every line twice.
180
+ """
181
+ root = logging.getLogger()
182
+ for existing in root.handlers:
183
+ if getattr(existing, "_agentic_auth_json", False):
184
+ return existing
185
+
186
+ handler = stream_handler or logging.StreamHandler()
187
+ handler.setFormatter(JsonFormatter())
188
+ handler.addFilter(DispatchPathFilter())
189
+ handler._agentic_auth_json = True # type: ignore[attr-defined]
190
+ root.addHandler(handler)
191
+ return handler
@@ -0,0 +1,169 @@
1
+ """Enforcement-point telemetry: the registry, the two routes, and the outcome mapping.
2
+
3
+ Before this module, nothing under ``agentic_auth/sidecar/`` emitted anything. The sidecar is the
4
+ component that actually blocks calls, fail-closes when the control plane is unreachable, and
5
+ runs in observe mode — so a sidecar that had been silently forwarding every call looked exactly
6
+ like a healthy one. These are the series that tell the difference.
7
+
8
+ The mapping in :func:`classify` is the heart of it. ``enforce()`` has around twenty return
9
+ paths, but every one of them already produces an
10
+ :class:`~agentic_auth.sidecar.enforce.EdgeAttribution`
11
+ with an outcome and a reason — so one mapping covers them all, rather than twenty call sites
12
+ each remembering to increment the right counter. The classification reuses the codebase's own
13
+ ``POLICY_REASONS`` / ``INFRASTRUCTURE_REASONS`` split, which is already exactly the
14
+ distinction, instead of inventing a parallel one that could disagree with it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import time
20
+ from dataclasses import dataclass
21
+ from typing import TYPE_CHECKING
22
+
23
+ from agentic_auth.observability import surface
24
+ from agentic_auth.schemas.authorize import INFRASTRUCTURE_REASONS, POLICY_REASONS, DenyReason
25
+
26
+ if TYPE_CHECKING: # pragma: no cover - typing only
27
+ from agentic_auth.services.metrics import PepMetrics
28
+
29
+ # EdgeAttribution.outcome values, from agentic_auth/sidecar/enforce.py.
30
+ EDGE_ALLOW = "allow"
31
+ EDGE_DENY = "deny"
32
+ EDGE_OBSERVED = "observed"
33
+ EDGE_BLOCKED_INFRA = "blocked_infra"
34
+ EDGE_BLOCKED_LOCAL = "blocked_local"
35
+
36
+ # Sidecar-local refusal codes (agentic_auth/sidecar/deny.py) -> block cause. These are the caller's
37
+ # problem or a configuration problem, never a guardrail outage, so none of them is in
38
+ # PEP_INFRA_BLOCK_CAUSES and none of them pages.
39
+ _LOCAL_CAUSES = {
40
+ "UPSTREAM_NOT_MAPPED": "unresolvable_call",
41
+ "TARGET_NOT_RESOLVED": "unresolvable_call",
42
+ "UNAUTHORIZED": "unauthorized",
43
+ "BODY_TOO_LARGE_TO_BIND": "body_too_large",
44
+ "PARAMS_NOT_AN_OBJECT": "unbindable",
45
+ "TRANSACTION_SERVICE_UNAVAILABLE": "mint_unreachable",
46
+ }
47
+
48
+ # Infrastructure DenyReason -> block cause. Each names which dependency failed, because
49
+ # "the guardrail is broken" is only actionable if it says which part.
50
+ _INFRA_CAUSES = {
51
+ DenyReason.PDP_UNAVAILABLE.value: "pdp_unreachable",
52
+ DenyReason.TOKEN_SERVICE_UNAVAILABLE.value: "exchange_unreachable",
53
+ DenyReason.AUDIT_UNAVAILABLE.value: "audit_unavailable",
54
+ }
55
+
56
+ _POLICY_REASON_VALUES = frozenset(r.value for r in POLICY_REASONS)
57
+ _INFRA_REASON_VALUES = frozenset(r.value for r in INFRASTRUCTURE_REASONS)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Classification:
62
+ """What one proxied call was, in telemetry terms."""
63
+
64
+ outcome: str
65
+ block_cause: str | None
66
+
67
+ @property
68
+ def is_infra_failure(self) -> bool:
69
+ """The guardrail refused because it could not do its job, not because policy said no.
70
+ This is the distinction the cause label exists for."""
71
+ return self.block_cause in surface.PEP_INFRA_BLOCK_CAUSES
72
+
73
+
74
+ def classify(edge_outcome: str, reason: str | None) -> Classification:
75
+ """Map an ``EdgeAttribution`` to a PEP outcome and block cause.
76
+
77
+ Unrecognised inputs fall through to ``other`` rather than being dropped: a path nobody
78
+ mapped should show up as an odd label value on a dashboard, not as a call that never
79
+ happened.
80
+ """
81
+ if edge_outcome == EDGE_ALLOW:
82
+ return Classification("allowed", None)
83
+
84
+ if edge_outcome == EDGE_OBSERVED:
85
+ # Forwarded, but refused on the merits. Never folded into `allowed`, or observe mode
86
+ # would read as a working guardrail; never into `blocked`, or it would overstate what
87
+ # the enforcement point actually did.
88
+ return Classification("observed_would_block", "policy")
89
+
90
+ if edge_outcome == EDGE_DENY:
91
+ # A policy verdict. `deny` is only ever constructed for POLICY_REASONS in enforce(),
92
+ # but the reason is checked rather than assumed, so a future change that routes an
93
+ # infrastructure reason here is visible instead of mislabelled as policy.
94
+ if reason in _INFRA_REASON_VALUES:
95
+ return Classification("blocked", _INFRA_CAUSES[reason])
96
+ if reason in _POLICY_REASON_VALUES:
97
+ return Classification("blocked", "policy")
98
+ return Classification("blocked", _LOCAL_CAUSES.get(reason or "", "other"))
99
+
100
+ if edge_outcome == EDGE_BLOCKED_INFRA:
101
+ cause = _INFRA_CAUSES.get(reason or "") or _LOCAL_CAUSES.get(reason or "")
102
+ return Classification("blocked", cause or "other")
103
+
104
+ if edge_outcome == EDGE_BLOCKED_LOCAL:
105
+ return Classification("blocked", _LOCAL_CAUSES.get(reason or "", "other"))
106
+
107
+ return Classification("blocked", "other")
108
+
109
+
110
+ class StageTimer:
111
+ """Accumulates per-stage durations for one proxied call.
112
+
113
+ Overhead is reported as *total minus upstream* rather than as a separately accumulated
114
+ number, so the two can be cross-checked: if ``overhead`` stops tracking the sum of the
115
+ non-upstream stages, there is unaccounted time inside the enforcement point.
116
+ """
117
+
118
+ __slots__ = ("_metrics", "_stages", "_started")
119
+
120
+ def __init__(self, metrics: PepMetrics | None) -> None:
121
+ self._metrics = metrics
122
+ self._stages: dict[str, float] = {}
123
+ self._started = time.perf_counter()
124
+
125
+ def stage(self, name: str) -> _StageContext:
126
+ return _StageContext(self, name)
127
+
128
+ def _record(self, name: str, seconds: float) -> None:
129
+ self._stages[name] = self._stages.get(name, 0.0) + seconds
130
+ if self._metrics is not None and name in surface.PEP_STAGES:
131
+ self._metrics.stage_duration.labels(stage=name).observe(seconds)
132
+
133
+ def finish(self) -> None:
134
+ """Record the guardrail's own added time. Called once, after the call completes."""
135
+ if self._metrics is None:
136
+ return
137
+ total = time.perf_counter() - self._started
138
+ overhead = total - self._stages.get("upstream", 0.0)
139
+ self._metrics.overhead.observe(max(0.0, overhead))
140
+
141
+ @property
142
+ def stages(self) -> dict[str, float]:
143
+ return dict(self._stages)
144
+
145
+
146
+ class _StageContext:
147
+ __slots__ = ("_name", "_started", "_timer")
148
+
149
+ def __init__(self, timer: StageTimer, name: str) -> None:
150
+ self._timer = timer
151
+ self._name = name
152
+
153
+ def __enter__(self) -> _StageContext:
154
+ self._started = time.perf_counter()
155
+ return self
156
+
157
+ def __exit__(self, *exc: object) -> None:
158
+ # Recorded even when the stage raised: an unreachable control plane is exactly the
159
+ # latency an operator needs to see, and dropping it would make an outage look fast.
160
+ self._timer._record(self._name, time.perf_counter() - self._started)
161
+
162
+
163
+ def record(metrics: PepMetrics | None, classification: Classification) -> None:
164
+ """Increment the call and block counters for one proxied call."""
165
+ if metrics is None:
166
+ return
167
+ metrics.calls.labels(outcome=classification.outcome).inc()
168
+ if classification.block_cause is not None and classification.outcome == "blocked":
169
+ metrics.blocks.labels(cause=classification.block_cause).inc()