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,225 @@
1
+ """Typed attribute builders — the one place the allowlist and the disclosure rule are applied.
2
+
3
+ Every span attribute this layer emits is produced here. Nothing else constructs attribute dicts,
4
+ so there is exactly one place to audit for two rules: no secrets, and pseudonymous by
5
+ default), and exactly one place a test has to sweep.
6
+
7
+ Two behaviours that look inconsistent but are not:
8
+
9
+ - **In tests, an attribute outside the contract raises.** In production it is dropped and the
10
+ span is emitted without it. Telemetry must never be the reason a request fails, but a
11
+ key that escaped review must never ship quietly either. ``_STRICT`` is on under pytest.
12
+ - **A pseudonym and its plaintext counterpart are never both present.** A backend that received
13
+ both would hold two spellings of one identity, which defeats the point of the default.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from typing import Any
20
+
21
+ from agentic_auth.observability import surface
22
+ from agentic_auth.observability.config import ObservabilityConfig
23
+ from agentic_auth.observability.ids import KIND_AGENT, KIND_CHAIN, KIND_TARGET, pseudonym
24
+
25
+ # Raise rather than drop when running under pytest, so a contract violation fails a build
26
+ # instead of silently thinning the surface.
27
+ _STRICT = "PYTEST_CURRENT_TEST" in os.environ or bool(
28
+ os.environ.get("AGENTIC_AUTH_TELEMETRY_STRICT")
29
+ )
30
+
31
+ Attributes = dict[str, Any]
32
+
33
+
34
+ def _put(attrs: Attributes, key: str, value: Any) -> None:
35
+ """Set one attribute, refusing anything outside the contract.
36
+
37
+ ``None`` is dropped rather than exported: an absent attribute and an attribute explicitly
38
+ set to null read differently in every backend, and "we did not know" is better expressed by
39
+ absence.
40
+ """
41
+ if value is None:
42
+ return
43
+ reason = surface.forbidden_reason(key)
44
+ if reason is not None:
45
+ if _STRICT:
46
+ raise AssertionError(f"telemetry surface violation: {reason}")
47
+ return
48
+ allowed = surface.ATTR_VALUES.get(key)
49
+ if allowed is not None and isinstance(value, str) and value not in allowed:
50
+ if _STRICT:
51
+ raise AssertionError(f"{key}={value!r} is not a declared value for {key}")
52
+ return
53
+ attrs[key] = value
54
+
55
+
56
+ def _identity(
57
+ attrs: Attributes,
58
+ config: ObservabilityConfig,
59
+ *,
60
+ agent: str | None,
61
+ act_chain: str | None,
62
+ taint_source: str | None,
63
+ ) -> None:
64
+ """Pseudonymous by default, plaintext only with the explicit opt-in, never both.
65
+
66
+ The chain is pseudonymised as one value rather than per actor. A per-actor list would let an
67
+ observer count the hops and correlate repeated actors across sessions, which is most of what
68
+ the plaintext chain would have told them.
69
+ """
70
+ if config.identity_disclosure:
71
+ _put(attrs, surface.ATTR_AGENT, agent)
72
+ _put(attrs, surface.ATTR_ACT_CHAIN, act_chain)
73
+ _put(attrs, surface.ATTR_TAINT_SOURCE, taint_source)
74
+ return
75
+
76
+ if agent is not None:
77
+ _put(attrs, surface.ATTR_AGENT_REF, pseudonym(KIND_AGENT, agent, config.key))
78
+ if act_chain is not None:
79
+ _put(attrs, surface.ATTR_ACT_CHAIN_REF, pseudonym(KIND_CHAIN, act_chain, config.key))
80
+ if taint_source is not None:
81
+ _put(attrs, surface.ATTR_TAINT_SOURCE_REF, pseudonym(KIND_TARGET, taint_source, config.key))
82
+
83
+
84
+ def chain_digest(act_chain: list[Any] | None) -> str | None:
85
+ """Flatten a verified act chain into one stable string for pseudonymisation.
86
+
87
+ Order matters — ``user:alice > router > billing`` is a different delegation from
88
+ ``user:alice > billing > router`` — so the separator is positional, not a set.
89
+ """
90
+ if not act_chain:
91
+ return None
92
+ parts: list[str] = []
93
+ for actor in act_chain:
94
+ if isinstance(actor, dict):
95
+ parts.append(str(actor.get("sub") or actor.get("agent") or actor))
96
+ else:
97
+ parts.append(str(actor))
98
+ return ">".join(parts)
99
+
100
+
101
+ def decision_attributes(
102
+ config: ObservabilityConfig,
103
+ *,
104
+ action_id: str | None,
105
+ session_id: str,
106
+ hop: int,
107
+ outcome: str,
108
+ deny_reason: str | None,
109
+ recoverable: bool,
110
+ enforced: bool,
111
+ target_kind: str,
112
+ data_class: str,
113
+ privileged: bool,
114
+ taint: str | None,
115
+ policy_version: int,
116
+ guarantee_level: str | None = None,
117
+ acting_agent: str | None = None,
118
+ act_chain: list[Any] | None = None,
119
+ taint_source: str | None = None,
120
+ ) -> Attributes:
121
+ """``authz.decide``.
122
+
123
+ ``action_id`` is the pointer the whole feature turns on: it resolves through
124
+ ``GET /v1/audit/actions/{action_id}/chain`` to the verified delegation chain. It is ``None``
125
+ only when the audit write itself failed, in which case the outcome is a deny with
126
+ ``AUDIT_UNAVAILABLE`` — a span with neither is a bug, asserted in the integration tests.
127
+ """
128
+ attrs: Attributes = {}
129
+ _put(attrs, surface.ATTR_ACTION_ID, action_id)
130
+ _put(attrs, surface.ATTR_SESSION_ID, session_id)
131
+ _put(attrs, surface.ATTR_HOP, hop)
132
+ _put(attrs, surface.ATTR_OUTCOME, outcome)
133
+ _put(attrs, surface.ATTR_DENY_REASON, deny_reason)
134
+ _put(attrs, surface.ATTR_RECOVERABLE, recoverable)
135
+ _put(attrs, surface.ATTR_ENFORCED, enforced)
136
+ _put(attrs, surface.ATTR_TARGET_KIND, target_kind)
137
+ _put(attrs, surface.ATTR_DATA_CLASS, data_class)
138
+ _put(attrs, surface.ATTR_PRIVILEGED, privileged)
139
+ _put(attrs, surface.ATTR_TAINT, taint)
140
+ _put(attrs, surface.ATTR_POLICY_VERSION, policy_version)
141
+ _put(attrs, surface.ATTR_GUARANTEE_LEVEL, guarantee_level)
142
+ _identity(
143
+ attrs,
144
+ config,
145
+ agent=acting_agent,
146
+ act_chain=chain_digest(act_chain),
147
+ taint_source=taint_source,
148
+ )
149
+ return attrs
150
+
151
+
152
+ def exchange_attributes(
153
+ config: ObservabilityConfig,
154
+ *,
155
+ action_id: str | None,
156
+ session_id: str | None,
157
+ hop: int | None,
158
+ result: str,
159
+ pop_failure_cause: str | None = None,
160
+ policy_version: int | None = None,
161
+ acting_agent: str | None = None,
162
+ ) -> Attributes:
163
+ """``authz.exchange``. Never a token, a ``jti``, or a subject token — ``_put`` refuses those
164
+ keys by substring, so this is enforced rather than merely intended."""
165
+ attrs: Attributes = {}
166
+ _put(attrs, surface.ATTR_ACTION_ID, action_id)
167
+ _put(attrs, surface.ATTR_SESSION_ID, session_id)
168
+ _put(attrs, surface.ATTR_HOP, hop)
169
+ _put(attrs, surface.ATTR_RESULT, result)
170
+ _put(attrs, surface.ATTR_POP_FAILURE_CAUSE, pop_failure_cause)
171
+ _put(attrs, surface.ATTR_POLICY_VERSION, policy_version)
172
+ _identity(attrs, config, agent=acting_agent, act_chain=None, taint_source=None)
173
+ return attrs
174
+
175
+
176
+ def mint_attributes(
177
+ config: ObservabilityConfig,
178
+ *,
179
+ action_id: str | None,
180
+ session_id: str | None,
181
+ result: str,
182
+ policy_version: int | None = None,
183
+ acting_agent: str | None = None,
184
+ ) -> Attributes:
185
+ """``authz.transaction.mint``. Records *that* a binding was computed, never the binding, the
186
+ ``params_hash``, or any part of the request body."""
187
+ attrs: Attributes = {}
188
+ _put(attrs, surface.ATTR_ACTION_ID, action_id)
189
+ _put(attrs, surface.ATTR_SESSION_ID, session_id)
190
+ _put(attrs, surface.ATTR_RESULT, result)
191
+ _put(attrs, surface.ATTR_POLICY_VERSION, policy_version)
192
+ _identity(attrs, config, agent=acting_agent, act_chain=None, taint_source=None)
193
+ return attrs
194
+
195
+
196
+ def pep_attributes(
197
+ config: ObservabilityConfig,
198
+ *,
199
+ mode: str,
200
+ outcome: str,
201
+ block_cause: str | None = None,
202
+ action_id: str | None = None,
203
+ session_id: str | None = None,
204
+ hop: int | None = None,
205
+ http_method: str | None = None,
206
+ http_status: int | None = None,
207
+ error_type: str | None = None,
208
+ ) -> Attributes:
209
+ """``pep.forward``.
210
+
211
+ ``outcome="observed_would_block"`` is its own value, never folded into ``allowed``: the call
212
+ was forwarded, but it was refused on the merits, and collapsing the two would make observe
213
+ mode read as a working guardrail.
214
+ """
215
+ attrs: Attributes = {}
216
+ _put(attrs, surface.ATTR_PEP_MODE, mode)
217
+ _put(attrs, surface.ATTR_PEP_OUTCOME, outcome)
218
+ _put(attrs, surface.ATTR_PEP_BLOCK_CAUSE, block_cause)
219
+ _put(attrs, surface.ATTR_ACTION_ID, action_id)
220
+ _put(attrs, surface.ATTR_SESSION_ID, session_id)
221
+ _put(attrs, surface.ATTR_HOP, hop)
222
+ _put(attrs, surface.ATTR_HTTP_METHOD, http_method)
223
+ _put(attrs, surface.ATTR_HTTP_STATUS, http_status)
224
+ _put(attrs, surface.ATTR_ERROR_TYPE, error_type)
225
+ return attrs
@@ -0,0 +1,286 @@
1
+ """The telemetry surface: every name this layer is permitted to emit.
2
+
3
+ One module, consumed by the attribute builders *and* by the tests, so the contract and the code
4
+ cannot drift apart. The same pattern as ``agentic_auth/services/edge_rules.py``, which Phase 3 made
5
+ the single shared rule module with ``test_edge_rules_parity.py`` holding runtime and CI to it.
6
+
7
+ https://authzai.dev/reference/telemetry-surface is the human-readable half, and
8
+ ``tests/unit/test_telemetry_surface.py`` fails if the two enumerate different sets.
9
+
10
+ Two rules this module enforces mechanically:
11
+
12
+ - **Nothing outside these sets is ever emitted.** A builder that tries is a bug in tests and
13
+ drops the key in production — telemetry must never be the reason a request fails.
14
+ - **No key collides with a reserved OpenTelemetry name** except where we deliberately reuse a
15
+ standard one with its standard meaning (``error.type`` and the HTTP conventions).
16
+
17
+ Pure data and pure functions only. No imports beyond the standard library, so the tests run
18
+ without the ``otel`` extra installed.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from types import MappingProxyType
24
+
25
+ # ----------------------------------------------------------------------------- span names
26
+
27
+ SPAN_DECIDE = "authz.decide"
28
+ SPAN_EXCHANGE = "authz.exchange"
29
+ SPAN_MINT = "authz.transaction.mint"
30
+ SPAN_PEP_FORWARD = "pep.forward"
31
+ SPAN_PEP_DECIDE = "pep.decide"
32
+ SPAN_PEP_EXCHANGE = "pep.exchange"
33
+ SPAN_PEP_MINT = "pep.mint"
34
+ SPAN_PEP_UPSTREAM = "pep.upstream"
35
+
36
+ SPAN_NAMES = frozenset(
37
+ {
38
+ SPAN_DECIDE,
39
+ SPAN_EXCHANGE,
40
+ SPAN_MINT,
41
+ SPAN_PEP_FORWARD,
42
+ SPAN_PEP_DECIDE,
43
+ SPAN_PEP_EXCHANGE,
44
+ SPAN_PEP_MINT,
45
+ SPAN_PEP_UPSTREAM,
46
+ }
47
+ )
48
+
49
+ # Spans emitted on the dispatch path. These never record an exception: the SDK would attach
50
+ # `exception.message` and a full `exception.stacktrace`, and a traceback through token
51
+ # verification can carry a token fragment.
52
+ DISPATCH_PATH_SPANS = SPAN_NAMES
53
+
54
+ # ------------------------------------------------------------------------ attribute keys
55
+
56
+ # Correlation. Opaque UUIDs that carry no identity on their own and are useless without the
57
+ # audit-reader check — they are the pointer from a trace back to the audit record, so they are NOT
58
+ # pseudonymised.
59
+ ATTR_ACTION_ID = "authz.action_id"
60
+ ATTR_SESSION_ID = "authz.session_id"
61
+ ATTR_HOP = "authz.hop"
62
+
63
+ # The decision.
64
+ ATTR_OUTCOME = "authz.outcome"
65
+ ATTR_DENY_REASON = "authz.deny_reason"
66
+ ATTR_RECOVERABLE = "authz.recoverable"
67
+ ATTR_ENFORCED = "authz.enforced"
68
+ ATTR_TARGET_KIND = "authz.target_kind"
69
+ ATTR_DATA_CLASS = "authz.data_class"
70
+ ATTR_PRIVILEGED = "authz.privileged"
71
+ ATTR_TAINT = "authz.taint"
72
+ ATTR_POLICY_VERSION = "authz.policy_version"
73
+ # Phase 5. How strong the enforcement actually was for this hop, as the enforcement point
74
+ # reported it. "How much traffic ran below full guarantee" is an operator question, so it
75
+ # belongs on the span as well as in the audit row.
76
+ ATTR_GUARANTEE_LEVEL = "authz.guarantee_level"
77
+
78
+ # Exchange / mint.
79
+ ATTR_RESULT = "authz.result"
80
+ ATTR_POP_FAILURE_CAUSE = "authz.pop_failure_cause"
81
+
82
+ # Enforcement point.
83
+ ATTR_PEP_MODE = "authz.pep.mode"
84
+ ATTR_PEP_OUTCOME = "authz.pep.outcome"
85
+ ATTR_PEP_BLOCK_CAUSE = "authz.pep.block_cause"
86
+
87
+ # Identity. Pseudonymous by default; the plaintext forms appear only with the disclosure opt-in,
88
+ # and never alongside their `_ref` counterpart.
89
+ ATTR_AGENT_REF = "authz.agent_ref"
90
+ ATTR_ACT_CHAIN_REF = "authz.act_chain_ref"
91
+ ATTR_TAINT_SOURCE_REF = "authz.taint_source_ref"
92
+ ATTR_AGENT = "authz.agent"
93
+ ATTR_ACT_CHAIN = "authz.act_chain"
94
+ ATTR_TAINT_SOURCE = "authz.taint_source"
95
+
96
+ PSEUDONYMOUS_ATTRS = frozenset({ATTR_AGENT_REF, ATTR_ACT_CHAIN_REF, ATTR_TAINT_SOURCE_REF})
97
+ DISCLOSED_ATTRS = frozenset({ATTR_AGENT, ATTR_ACT_CHAIN, ATTR_TAINT_SOURCE})
98
+
99
+ # Standard conventions, reused with their standard meaning.
100
+ ATTR_ERROR_TYPE = "error.type"
101
+ ATTR_HTTP_METHOD = "http.request.method"
102
+ ATTR_HTTP_STATUS = "http.response.status_code"
103
+
104
+ SEMCONV_ATTRS = frozenset({ATTR_ERROR_TYPE, ATTR_HTTP_METHOD, ATTR_HTTP_STATUS})
105
+
106
+ ATTR_KEYS = (
107
+ frozenset(
108
+ {
109
+ ATTR_ACTION_ID,
110
+ ATTR_SESSION_ID,
111
+ ATTR_HOP,
112
+ ATTR_OUTCOME,
113
+ ATTR_DENY_REASON,
114
+ ATTR_RECOVERABLE,
115
+ ATTR_ENFORCED,
116
+ ATTR_TARGET_KIND,
117
+ ATTR_DATA_CLASS,
118
+ ATTR_PRIVILEGED,
119
+ ATTR_TAINT,
120
+ ATTR_POLICY_VERSION,
121
+ ATTR_GUARANTEE_LEVEL,
122
+ ATTR_RESULT,
123
+ ATTR_POP_FAILURE_CAUSE,
124
+ ATTR_PEP_MODE,
125
+ ATTR_PEP_OUTCOME,
126
+ ATTR_PEP_BLOCK_CAUSE,
127
+ }
128
+ )
129
+ | PSEUDONYMOUS_ATTRS
130
+ | DISCLOSED_ATTRS
131
+ | SEMCONV_ATTRS
132
+ )
133
+
134
+ # Never an attribute, on any span, at any disclosure setting. Checked by name so a future
135
+ # refactor that starts passing one of these through fails loudly.
136
+ FORBIDDEN_ATTR_SUBSTRINGS = (
137
+ "token",
138
+ "jti",
139
+ "secret",
140
+ "credential",
141
+ "password",
142
+ "authorization",
143
+ "body",
144
+ "params_hash",
145
+ "binding",
146
+ "query",
147
+ "stacktrace",
148
+ )
149
+
150
+ # ------------------------------------------------------------------- structured log fields
151
+
152
+ LOG_COMPONENT = "authz.component"
153
+ LOG_FIELDS = frozenset({LOG_COMPONENT, ATTR_SESSION_ID, ATTR_ACTION_ID, ATTR_HOP, ATTR_ERROR_TYPE})
154
+
155
+ COMPONENT_CONTROL_PLANE = "control_plane"
156
+ COMPONENT_PEP = "pep"
157
+ COMPONENT_VERIFIER = "verifier"
158
+ COMPONENT_CLI = "cli"
159
+ COMPONENTS = frozenset({COMPONENT_CONTROL_PLANE, COMPONENT_PEP, COMPONENT_VERIFIER, COMPONENT_CLI})
160
+
161
+ # ----------------------------------------------------------------------------- metrics
162
+
163
+ # New families only. The Phase 3/4 families are owned by agentic_auth/services/metrics.py and
164
+ # asserted
165
+ # unchanged by tests/unit/test_metric_compatibility.py — this layer must not restate them, or
166
+ # there would be two places to update and one would rot.
167
+ METRIC_PEP_CALLS = "agentic_auth_pep_calls"
168
+ METRIC_PEP_BLOCKS = "agentic_auth_pep_blocks"
169
+ METRIC_PEP_STAGE_DURATION = "agentic_auth_pep_stage_duration_seconds"
170
+ METRIC_PEP_OVERHEAD = "agentic_auth_pep_overhead_seconds"
171
+ METRIC_PEP_UP = "agentic_auth_pep_up"
172
+ METRIC_PEP_INFO = "agentic_auth_pep_info"
173
+ METRIC_TRACE_CONTEXT_REJECTED = "agentic_auth_trace_context_rejected"
174
+ METRIC_TELEMETRY_DROPPED = "agentic_auth_telemetry_dropped"
175
+ METRIC_IDENTITY_DISCLOSURE = "agentic_auth_telemetry_identity_disclosure"
176
+
177
+ NEW_METRIC_NAMES = frozenset(
178
+ {
179
+ METRIC_PEP_CALLS,
180
+ METRIC_PEP_BLOCKS,
181
+ METRIC_PEP_STAGE_DURATION,
182
+ METRIC_PEP_OVERHEAD,
183
+ METRIC_PEP_UP,
184
+ METRIC_PEP_INFO,
185
+ METRIC_TRACE_CONTEXT_REJECTED,
186
+ METRIC_TELEMETRY_DROPPED,
187
+ METRIC_IDENTITY_DISCLOSURE,
188
+ }
189
+ )
190
+
191
+ # ------------------------------------------------------------------ closed value sets
192
+ #
193
+ # Every label value and every enum attribute value, enumerated. This is what bounds metric
194
+ # cardinality regardless of how many agents, sessions or targets exist, and
195
+ # what lets test_dashboard_artifacts.py catch a typo'd matcher like {cause="pdp_unavailable"}
196
+ # against the real value `pdp_unreachable`.
197
+
198
+ PEP_OUTCOMES = frozenset({"allowed", "blocked", "observed_would_block"})
199
+ # Derived by enumerating every return path in agentic_auth/sidecar/enforce.py, not from a guess. The
200
+ # planning draft listed six; four more are needed to cover the code as written:
201
+ # audit_unavailable the contract names "audit record not committed" explicitly, and enforce()
202
+ # refuses on it (DenyReason.AUDIT_UNAVAILABLE)
203
+ # unauthorized a missing/malformed/refused bearer: the caller's fault, so neither a
204
+ # policy verdict nor a guardrail outage
205
+ # unbindable a privileged call whose body is not a JSON object
206
+ # other a cause we failed to classify; present so an unmapped path shows up as
207
+ # an odd label value rather than as a call that never happened
208
+ PEP_BLOCK_CAUSES = frozenset(
209
+ {
210
+ "policy",
211
+ "pdp_unreachable",
212
+ "exchange_unreachable",
213
+ "mint_unreachable",
214
+ "audit_unavailable",
215
+ "body_too_large",
216
+ "unbindable",
217
+ "unauthorized",
218
+ "unresolvable_call",
219
+ "other",
220
+ }
221
+ )
222
+ # Refusals caused by the guardrail's own unavailability rather than by policy. The distinction
223
+ # the cause label exists for: the difference between a guardrail that works and one that is broken.
224
+ # Refusals caused by the guardrail's own unavailability rather than by policy: the
225
+ # distinction, and the only causes that page. `unauthorized`, `unbindable`, `body_too_large`
226
+ # and `unresolvable_call` are deliberately absent — they are the caller's or the operator's
227
+ # mistake, and alerting on them would cry wolf.
228
+ PEP_INFRA_BLOCK_CAUSES = frozenset(
229
+ {"pdp_unreachable", "exchange_unreachable", "mint_unreachable", "audit_unavailable"}
230
+ )
231
+ PEP_MODE_ENFORCING = "enforcing"
232
+ PEP_MODE_OBSERVING = "observing"
233
+ PEP_MODES = frozenset({PEP_MODE_ENFORCING, PEP_MODE_OBSERVING})
234
+ PEP_STAGES = frozenset({"decide", "exchange", "mint", "upstream"})
235
+ TRACE_CONTEXT_REJECT_CAUSES = frozenset({"malformed", "absent", "baggage_dropped"})
236
+ TELEMETRY_SIGNALS = frozenset({"span", "log"})
237
+ OUTCOMES = frozenset({"allow", "deny"})
238
+ TARGET_KINDS = frozenset({"tool", "agent"})
239
+ TAINTS = frozenset({"trusted_internal", "untrusted_external"})
240
+ # agentic_auth.boundary.guarantee.Guarantee, mirrored here so this module keeps importing nothing.
241
+ GUARANTEE_LEVELS = frozenset({"full", "connector", "network", "consent_only"})
242
+
243
+ LABEL_VALUES: MappingProxyType[str, frozenset[str]] = MappingProxyType(
244
+ {
245
+ f"{METRIC_PEP_CALLS}:outcome": PEP_OUTCOMES,
246
+ f"{METRIC_PEP_BLOCKS}:cause": PEP_BLOCK_CAUSES,
247
+ f"{METRIC_PEP_STAGE_DURATION}:stage": PEP_STAGES,
248
+ f"{METRIC_PEP_INFO}:mode": PEP_MODES,
249
+ f"{METRIC_TRACE_CONTEXT_REJECTED}:cause": TRACE_CONTEXT_REJECT_CAUSES,
250
+ f"{METRIC_TELEMETRY_DROPPED}:signal": TELEMETRY_SIGNALS,
251
+ }
252
+ )
253
+
254
+ ATTR_VALUES: MappingProxyType[str, frozenset[str]] = MappingProxyType(
255
+ {
256
+ ATTR_OUTCOME: OUTCOMES,
257
+ ATTR_TARGET_KIND: TARGET_KINDS,
258
+ ATTR_TAINT: TAINTS,
259
+ ATTR_GUARANTEE_LEVEL: GUARANTEE_LEVELS,
260
+ ATTR_PEP_MODE: PEP_MODES,
261
+ ATTR_PEP_OUTCOME: PEP_OUTCOMES,
262
+ ATTR_PEP_BLOCK_CAUSE: PEP_BLOCK_CAUSES,
263
+ }
264
+ )
265
+
266
+ # --------------------------------------------------------------------------- validation
267
+
268
+
269
+ def is_permitted_attr(key: str) -> bool:
270
+ return key in ATTR_KEYS
271
+
272
+
273
+ def forbidden_reason(key: str) -> str | None:
274
+ """Why ``key`` must never be emitted, or ``None`` if it is fine.
275
+
276
+ Checked by substring rather than by exact name so that a plausible future addition —
277
+ ``authz.subject_jti``, ``authz.request_body`` — is caught before it ships rather than after
278
+ it has been exported to somebody's backend.
279
+ """
280
+ if key in ATTR_KEYS:
281
+ return None
282
+ lowered = key.lower()
283
+ for needle in FORBIDDEN_ATTR_SUBSTRINGS:
284
+ if needle in lowered:
285
+ return f"{key!r} looks like a secret ({needle!r}) and is never emitted"
286
+ return f"{key!r} is not in the telemetry surface contract"
@@ -0,0 +1,167 @@
1
+ """The tracer provider, the sampler, and the refusal-preserving filter.
2
+
3
+ **Why sampling takes two mechanisms instead of one.** Every refusal must survive
4
+ the most aggressive sampling the layer permits, but ``Sampler.should_sample`` runs when a span
5
+ *starts* — before the outcome exists. So the work is split:
6
+
7
+ - ``AlwaysSampleAuthz`` keeps every span in our instrumentation scope at start, **ignoring the
8
+ parent's sampling decision**. An agent trace the integrator sampled out would otherwise take
9
+ our deny span with it. Spans that are not ours keep ordinary parent-based semantics, so
10
+ embedding this layer does not inflate an integrator's own trace volume.
11
+ - ``RefusalPreservingFilter`` sheds a fraction of ALLOW spans at ``on_end``, where the outcome
12
+ attribute exists. Refusals never consult the ratio.
13
+
14
+ The accepted consequence of overriding the parent is a **partial trace**: our span is exported,
15
+ its parent is not. That is fine — the span carries ``authz.action_id`` and resolves to the
16
+ verified delegation chain on its own. Losing the refusal would not be fine.
17
+
18
+ Everything here is best-effort. ``on_end`` runs synchronously on the thread that ended the span,
19
+ which on the control plane is a request-handling thread, so it does an attribute lookup and a
20
+ comparison and swallows any downstream failure.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import random
27
+ from collections.abc import Callable
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
31
+ from opentelemetry.sdk.trace.sampling import (
32
+ ALWAYS_ON,
33
+ Decision,
34
+ ParentBased,
35
+ Sampler,
36
+ SamplingResult,
37
+ )
38
+
39
+ from agentic_auth.observability import surface
40
+
41
+ if TYPE_CHECKING: # pragma: no cover - typing only
42
+ from collections.abc import Sequence
43
+
44
+ from opentelemetry.context import Context
45
+ from opentelemetry.trace import Link, SpanKind
46
+ from opentelemetry.trace.span import TraceState
47
+ from opentelemetry.util.types import Attributes
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ class AlwaysSampleAuthz(Sampler):
53
+ """Sample every authorization span, whatever the caller decided; defer otherwise.
54
+
55
+ Decision volume is one span per hop — bounded by authorizations, not by tokens or requests —
56
+ so always-on is affordable. ``RefusalPreservingFilter`` is what actually controls volume.
57
+ """
58
+
59
+ def __init__(self) -> None:
60
+ self._delegate = ParentBased(root=ALWAYS_ON)
61
+
62
+ def should_sample(
63
+ self,
64
+ parent_context: Context | None,
65
+ trace_id: int,
66
+ name: str,
67
+ kind: SpanKind | None = None,
68
+ attributes: Attributes = None,
69
+ links: Sequence[Link] | None = None,
70
+ trace_state: TraceState | None = None,
71
+ ) -> SamplingResult:
72
+ if name in surface.SPAN_NAMES:
73
+ # Carry the parent's trace state through rather than dropping it: the SDK docs
74
+ # recommend propagating it from the parent span context in a custom sampler.
75
+ return SamplingResult(Decision.RECORD_AND_SAMPLE, attributes, trace_state)
76
+ return self._delegate.should_sample(
77
+ parent_context, trace_id, name, kind, attributes, links, trace_state
78
+ )
79
+
80
+ def get_description(self) -> str:
81
+ return "AlwaysSampleAuthz{authz spans always sampled, others ParentBased(ALWAYS_ON)}"
82
+
83
+
84
+ class RefusalPreservingFilter(SpanProcessor):
85
+ """Shed allow spans; never shed a refusal.
86
+
87
+ Wraps the real exporting processor (normally a ``BatchSpanProcessor``) rather than exporting
88
+ itself, so batching, the bounded queue and the background export thread are all still the
89
+ SDK's.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ downstream: SpanProcessor,
95
+ allow_sample_ratio: float = 1.0,
96
+ on_drop: Callable[[], None] | None = None,
97
+ ) -> None:
98
+ self._downstream = downstream
99
+ self._ratio = min(1.0, max(0.0, allow_sample_ratio))
100
+ self._on_drop = on_drop
101
+
102
+ # -- classification --------------------------------------------------------------------
103
+
104
+ @staticmethod
105
+ def _is_refusal(attributes: Any) -> bool:
106
+ """Anything that is not an unambiguous allow is treated as a refusal.
107
+
108
+ Fail safe, deliberately: losing a signal we failed to classify is strictly worse than
109
+ exporting one span too many. A span with no attributes, or with attributes we do not
110
+ recognise, is kept.
111
+ """
112
+ if not attributes:
113
+ return True
114
+ outcome = attributes.get(surface.ATTR_OUTCOME)
115
+ pep_outcome = attributes.get(surface.ATTR_PEP_OUTCOME)
116
+ if outcome is None and pep_outcome is None:
117
+ return True
118
+ if outcome is not None and outcome != "allow":
119
+ return True
120
+ if pep_outcome is not None and pep_outcome != "allowed":
121
+ return True
122
+ # An error on an otherwise-allowed call still needs a human.
123
+ return attributes.get(surface.ATTR_ERROR_TYPE) is not None
124
+
125
+ def _keep(self, span: ReadableSpan) -> bool:
126
+ if span.name not in surface.DISPATCH_PATH_SPANS:
127
+ return True
128
+ if self._is_refusal(span.attributes):
129
+ return True
130
+ if self._ratio >= 1.0:
131
+ return True
132
+ if self._ratio <= 0.0:
133
+ return False
134
+ return random.random() < self._ratio
135
+
136
+ # -- SpanProcessor ---------------------------------------------------------------------
137
+
138
+ def on_start(self, span: Any, parent_context: Context | None = None) -> None:
139
+ try:
140
+ self._downstream.on_start(span, parent_context)
141
+ except Exception: # pragma: no cover - defensive; telemetry is never fatal
142
+ logger.debug("span processor on_start failed", exc_info=False)
143
+
144
+ def on_end(self, span: ReadableSpan) -> None:
145
+ try:
146
+ if self._keep(span):
147
+ self._downstream.on_end(span)
148
+ elif self._on_drop is not None:
149
+ # A sampling drop is telemetry loss and is counted as such.
150
+ self._on_drop()
151
+ except Exception: # pragma: no cover - defensive; telemetry is never fatal
152
+ # Swallowed on purpose. This runs on the thread that ended the span, which is a
153
+ # request-handling thread: a raise here would turn a telemetry fault into a failed
154
+ # authorization, which telemetry must never do.
155
+ logger.debug("span processor on_end failed", exc_info=False)
156
+
157
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
158
+ try:
159
+ return bool(self._downstream.force_flush(timeout_millis))
160
+ except Exception: # pragma: no cover - defensive
161
+ return False
162
+
163
+ def shutdown(self) -> None:
164
+ try:
165
+ self._downstream.shutdown()
166
+ except Exception: # pragma: no cover - defensive
167
+ logger.debug("span processor shutdown failed", exc_info=False)