cortexhub 0.4.2__tar.gz → 0.5.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. {cortexhub-0.4.2 → cortexhub-0.5.1}/PKG-INFO +1 -1
  2. {cortexhub-0.4.2 → cortexhub-0.5.1}/pyproject.toml +1 -1
  3. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/backend/client.py +96 -12
  4. cortexhub-0.5.1/src/cortexhub/policy/effects.py +249 -0
  5. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/policy/evaluator.py +26 -12
  6. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/policy/loader.py +20 -1
  7. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/policy/sync.py +52 -21
  8. cortexhub-0.4.2/src/cortexhub/policy/effects.py +0 -152
  9. {cortexhub-0.4.2 → cortexhub-0.5.1}/.gitignore +0 -0
  10. {cortexhub-0.4.2 → cortexhub-0.5.1}/LICENSE +0 -0
  11. {cortexhub-0.4.2 → cortexhub-0.5.1}/README.md +0 -0
  12. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/__init__.py +0 -0
  13. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/audit/__init__.py +0 -0
  14. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/audit/events.py +0 -0
  15. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/backend/__init__.py +0 -0
  16. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/client.py +0 -0
  17. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/config.py +0 -0
  18. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/constants.py +0 -0
  19. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/context/__init__.py +0 -0
  20. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/context/enricher.py +0 -0
  21. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/errors.py +0 -0
  22. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/__init__.py +0 -0
  23. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/injection.py +0 -0
  24. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/__init__.py +0 -0
  25. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSE +0 -0
  26. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSES_SOURCES +0 -0
  27. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/README.md +0 -0
  28. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/accuracy.json +0 -0
  29. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/attribute_ruler/patterns +0 -0
  30. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/config.cfg +0 -0
  31. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/lemmatizer/lookups/lookups.bin +0 -0
  32. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/meta.json +0 -0
  33. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/cfg +0 -0
  34. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/model +0 -0
  35. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/moves +0 -0
  36. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/cfg +0 -0
  37. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/model +0 -0
  38. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/moves +0 -0
  39. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/cfg +0 -0
  40. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/model +0 -0
  41. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/cfg +0 -0
  42. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/model +0 -0
  43. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/cfg +0 -0
  44. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/model +0 -0
  45. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tokenizer +0 -0
  46. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/key2row +0 -0
  47. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/lookups.bin +0 -0
  48. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/strings.json +0 -0
  49. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors +0 -0
  50. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors.cfg +0 -0
  51. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/models/en_core_web_sm/meta.json +0 -0
  52. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/pii.py +0 -0
  53. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/guardrails/secrets.py +0 -0
  54. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/interceptors/__init__.py +0 -0
  55. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/interceptors/mcp.py +0 -0
  56. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/logging.py +0 -0
  57. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/policy/__init__.py +0 -0
  58. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/policy/models.py +0 -0
  59. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/signing.py +0 -0
  60. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/telemetry/__init__.py +0 -0
  61. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/telemetry/otel.py +0 -0
  62. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/tool.py +0 -0
  63. {cortexhub-0.4.2 → cortexhub-0.5.1}/src/cortexhub/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cortexhub
3
- Version: 0.4.2
3
+ Version: 0.5.1
4
4
  Summary: CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "0.4.2"
3
+ version = "0.5.1"
4
4
  description = "CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10,<3.13"
@@ -2,15 +2,33 @@
2
2
 
3
3
  import os
4
4
  import re
5
- import structlog
6
- import httpx
7
- from typing import Any
8
5
  from dataclasses import dataclass
6
+ from typing import Any
9
7
 
8
+ import httpx
9
+ import structlog
10
10
 
11
11
  logger = structlog.get_logger(__name__)
12
12
 
13
13
 
14
+ def _extract_error_message(body: Any) -> str | None:
15
+ """Return a human‑readable error message from either the standard
16
+ CortexHub envelope ``{"error": {"code","message","details"}}`` or a
17
+ legacy FastAPI ``{"detail": "..."}`` body. Returns ``None`` when neither
18
+ shape is present."""
19
+ if not isinstance(body, dict):
20
+ return None
21
+ err = body.get("error")
22
+ if isinstance(err, dict):
23
+ msg = err.get("message")
24
+ if isinstance(msg, str) and msg:
25
+ return msg
26
+ detail = body.get("detail")
27
+ if isinstance(detail, str) and detail:
28
+ return detail
29
+ return None
30
+
31
+
14
32
  @dataclass
15
33
  class CustomPattern:
16
34
  """Custom regex pattern for detection."""
@@ -51,12 +69,23 @@ class PolicyBundle:
51
69
  - "off" : send raw data (dev/staging only)
52
70
 
53
71
  tool_policies: when present, SDK evaluates only the policies for the tool being invoked.
72
+
73
+ tool_classifications: connector-classifier output (bucket + risk) per tool,
74
+ used to match bucket-scoped policies. When a tool doesn't have a
75
+ tool-specific rule, the SDK falls back to the bucket policy for its
76
+ (connector_id, bucket). Keyed by tool name.
77
+
78
+ bucket_policies: bucket-scoped rules keyed by "<connector_id>::<bucket>".
79
+ Same shape as tool_policies entries (cedar/schema/policy_metadata).
54
80
  """
55
81
  version: str
56
82
  policies: str # Policy source text (empty when using per-tool bundles only)
57
83
  schema: dict[str, Any] | None = None # Merged schema when tool_policies not used
58
84
  policy_metadata: dict[str, dict[str, Any]] | None = None
59
85
  tool_policies: dict[str, dict[str, Any]] | None = None
86
+ # Bucket policies + classifications for SDK-side bucket match.
87
+ bucket_policies: dict[str, dict[str, Any]] | None = None
88
+ tool_classifications: dict[str, dict[str, str | None]] | None = None
60
89
  guardrail_configs: dict[str, GuardrailConfig] | None = None
61
90
  policy_defaults: dict[str, Any] | None = None
62
91
  policy_packs: list[dict[str, Any]] | None = None
@@ -134,7 +163,7 @@ class BackendClient:
134
163
  """
135
164
  if not self.agent_key or not self._client:
136
165
  return False, None
137
-
166
+
138
167
  try:
139
168
  # Note: base_url already includes /v1, so just /api-keys/validate.
140
169
  payload: dict[str, str] = {}
@@ -148,7 +177,7 @@ class BackendClient:
148
177
  json=payload if payload else None,
149
178
  timeout=5.0,
150
179
  )
151
-
180
+
152
181
  if response.status_code == 200:
153
182
  try:
154
183
  data = response.json()
@@ -160,12 +189,12 @@ class BackendClient:
160
189
  error=str(parse_err),
161
190
  )
162
191
  return False, None
163
-
192
+
164
193
  # Check if valid
165
194
  if not data.get("valid", False):
166
195
  logger.warning("Agent key validation failed", message=data.get("message"))
167
196
  return False, None
168
-
197
+
169
198
  # Parse policy bundle from backend
170
199
  # Backend returns: { policies: { version, policies: [...], privacy_mode }, guardrail_config?: {...} }
171
200
  # Guardrails are project-level only (validate returns guardrail_config when enabled).
@@ -248,7 +277,7 @@ class BackendClient:
248
277
  else:
249
278
  policies_str = raw_policies or ""
250
279
  policy_map = {}
251
-
280
+
252
281
  # Per-tool policies (preferred): backend sends tool_policies when available
253
282
  raw_tool_policies = policies_data.get("tool_policies")
254
283
  tool_policies: dict[str, dict[str, Any]] | None = None
@@ -262,6 +291,57 @@ class BackendClient:
262
291
  for k, v in raw_tool_policies.items()
263
292
  }
264
293
 
294
+ # Bucket-scoped policies: build per-(connector, bucket) entry
295
+ # from the raw policies list by inspecting match_connector_id /
296
+ # match_bucket. The same validate endpoint returns this shape
297
+ # when the control plane has connector-scoped policies.
298
+ bucket_policies: dict[str, dict[str, Any]] | None = None
299
+ raw_flat_policies = policies_data.get("policies") or []
300
+ if isinstance(raw_flat_policies, list):
301
+ bucket_acc: dict[str, dict[str, Any]] = {}
302
+ for p in raw_flat_policies:
303
+ if not isinstance(p, dict):
304
+ continue
305
+ mc = p.get("match_connector_id")
306
+ mb = p.get("match_bucket")
307
+ cedar_text = p.get("cedar_policy") or ""
308
+ if not (mc and mb and cedar_text):
309
+ continue
310
+ key = f"{mc}::{mb}"
311
+ bucket_acc[key] = {
312
+ "cedar": cedar_text,
313
+ "schema": None,
314
+ "policy_metadata": {
315
+ "policy0": {
316
+ "name": p.get("name"),
317
+ "effect": p.get("effect"),
318
+ "tool_name": None,
319
+ "policy_document_id": p.get("id"),
320
+ "approval_destination": p.get("approval_destination"),
321
+ "approval_webhook_id": p.get("approval_webhook_id"),
322
+ "approval_timeout_behavior": (
323
+ p.get("approval_timeout_behavior") or "deny"
324
+ ).lower(),
325
+ }
326
+ },
327
+ }
328
+ bucket_policies = bucket_acc or None
329
+
330
+ # Classification map: {tool_name → {bucket, risk, connector_id}}
331
+ raw_classifications = policies_data.get("tool_classifications")
332
+ tool_classifications: dict[str, dict[str, str | None]] | None = None
333
+ if isinstance(raw_classifications, dict) and raw_classifications:
334
+ tool_classifications = {
335
+ str(k): {
336
+ "bucket": (v.get("bucket") if isinstance(v, dict) else None),
337
+ "risk": (v.get("risk") if isinstance(v, dict) else None),
338
+ "connector_id": (
339
+ v.get("connector_id") if isinstance(v, dict) else None
340
+ ),
341
+ }
342
+ for k, v in raw_classifications.items()
343
+ }
344
+
265
345
  # privacy_mode may be in policies object or at top level (defensive)
266
346
  _privacy = policies_data.get("privacy_mode") or data.get("privacy_mode") or "on"
267
347
  policies = PolicyBundle(
@@ -270,6 +350,8 @@ class BackendClient:
270
350
  schema=policies_data.get("schema"),
271
351
  policy_metadata=policy_map,
272
352
  tool_policies=tool_policies,
353
+ bucket_policies=bucket_policies,
354
+ tool_classifications=tool_classifications,
273
355
  guardrail_configs=guardrail_configs if guardrail_configs else None,
274
356
  policy_defaults=policies_data.get("policy_defaults"),
275
357
  policy_packs=policies_data.get("policy_packs"),
@@ -278,7 +360,7 @@ class BackendClient:
278
360
  privacy_mode=_privacy,
279
361
  )
280
362
  logger.debug("Validate response privacy_mode", privacy_mode=_privacy)
281
-
363
+
282
364
  _aid = data.get("agent_id") or data.get("project_id") or ""
283
365
  _gid = data.get("group_id")
284
366
  config = SDKConfig(
@@ -317,9 +399,11 @@ class BackendClient:
317
399
  else:
318
400
  try:
319
401
  body = response.json()
320
- error_detail = body.get("detail", "Invalid agent key") if isinstance(body, dict) else str(body)
321
402
  except Exception:
322
- error_detail = (response.text or "")[:500] or f"HTTP {response.status_code}"
403
+ body = None
404
+ error_detail = _extract_error_message(body) or (
405
+ (response.text or "")[:500] or f"HTTP {response.status_code}"
406
+ )
323
407
  logger.warning("Agent key validation failed", error=error_detail)
324
408
  return False, None
325
409
 
@@ -332,7 +416,7 @@ class BackendClient:
332
416
  except Exception as e:
333
417
  logger.error("Agent key validation error", error=str(e))
334
418
  return False, None
335
-
419
+
336
420
  def close(self):
337
421
  """Close the HTTP client."""
338
422
  if self._client:
@@ -0,0 +1,249 @@
1
+ """Decision effects from policy evaluation.
2
+
3
+ Vocabulary follows the five AARM decisions:
4
+
5
+ * ``permit`` — allow the action as‑is.
6
+ * ``deny`` — block the action.
7
+ * ``modify`` — allow the action with rewritten arguments (PII redaction,
8
+ value clamps, field removal). ``redact`` is a narrower
9
+ synonym kept for dashboards that filter by it.
10
+ * ``step_up`` — require human approval before the action runs.
11
+ ``escalate`` is the historical SDK name and remains a
12
+ synonym so existing integrations keep working.
13
+ * ``defer`` — suspend the decision pending additional context (rarely
14
+ emitted by the SDK today; included so telemetry
15
+ vocabulary matches AARM end‑to‑end).
16
+
17
+ The evaluator is deterministic: the same ``AuthorizationRequest`` MUST
18
+ always produce the same ``Decision``.
19
+ """
20
+
21
+ from enum import Enum
22
+
23
+ from pydantic import BaseModel
24
+
25
+
26
+ class Effect(str, Enum):
27
+ """Policy decision effect (AARM R4)."""
28
+
29
+ PERMIT = "permit"
30
+ DENY = "deny"
31
+ MODIFY = "modify"
32
+ STEP_UP = "step_up"
33
+ DEFER = "defer"
34
+
35
+ # Historical SDK values — kept so existing customer code comparing
36
+ # ``decision.effect == Effect.ESCALATE`` keeps working. New code should
37
+ # prefer STEP_UP / MODIFY.
38
+ ESCALATE = "escalate"
39
+ REDACT = "redact"
40
+
41
+
42
+ class Decision(BaseModel):
43
+ """Result of policy evaluation.
44
+
45
+ Attributes
46
+ ----------
47
+ effect
48
+ One of the AARM decisions.
49
+ reasoning
50
+ Human‑readable explanation shown in span events and dashboards.
51
+ policy_id / policy_name
52
+ Which policy produced the decision.
53
+ policy_effect
54
+ Policy effect metadata (if available).
55
+ policy_decisions
56
+ All matching policy decisions (if available).
57
+ policy_timeout_behavior
58
+ For step‑up decisions: ``"deny"`` (default) or ``"allow"`` — what
59
+ happens when ``wait_for_approval`` times out.
60
+ modified_args
61
+ For ``modify`` decisions: the rewritten argument dict the tool
62
+ should be invoked with. ``None`` for other decisions.
63
+ """
64
+
65
+ effect: Effect
66
+ reasoning: str
67
+ policy_id: str | None = None
68
+ policy_name: str | None = None
69
+ policy_effect: str | None = None
70
+ policy_decisions: list[dict[str, str | None]] | None = None
71
+ policy_timeout_behavior: str | None = None
72
+ modified_args: dict[str, object] | None = None
73
+
74
+ # ── Predicates ───────────────────────────────────────────────────────
75
+ def is_allowed(self) -> bool:
76
+ """True for ``permit`` decisions."""
77
+ return self.effect == Effect.PERMIT
78
+
79
+ def is_denied(self) -> bool:
80
+ """True for ``deny`` decisions."""
81
+ return self.effect == Effect.DENY
82
+
83
+ def is_modified(self) -> bool:
84
+ """True when policy rewrote arguments (``modify`` or the legacy ``redact``)."""
85
+ return self.effect in (Effect.MODIFY, Effect.REDACT)
86
+
87
+ def is_redacted(self) -> bool:
88
+ """True specifically for the legacy ``redact`` effect."""
89
+ return self.effect == Effect.REDACT
90
+
91
+ def requires_approval(self) -> bool:
92
+ """True when human approval is required (``step_up`` / legacy ``escalate``)."""
93
+ return self.effect in (Effect.STEP_UP, Effect.ESCALATE)
94
+
95
+ def is_deferred(self) -> bool:
96
+ """True when the decision is suspended pending more context."""
97
+ return self.effect == Effect.DEFER
98
+
99
+ # ── Factories ────────────────────────────────────────────────────────
100
+ @classmethod
101
+ def permit(
102
+ cls,
103
+ reasoning: str = "Permitted by policy",
104
+ policy_id: str | None = None,
105
+ policy_name: str | None = None,
106
+ policy_effect: str | None = None,
107
+ policy_decisions: list[dict[str, str | None]] | None = None,
108
+ ) -> "Decision":
109
+ return cls(
110
+ effect=Effect.PERMIT,
111
+ reasoning=reasoning,
112
+ policy_id=policy_id,
113
+ policy_name=policy_name,
114
+ policy_effect=policy_effect,
115
+ policy_decisions=policy_decisions,
116
+ )
117
+
118
+ @classmethod
119
+ def allow(
120
+ cls,
121
+ reasoning: str = "Permitted by policy",
122
+ policy_id: str | None = None,
123
+ policy_name: str | None = None,
124
+ policy_effect: str | None = None,
125
+ policy_decisions: list[dict[str, str | None]] | None = None,
126
+ ) -> "Decision":
127
+ """Alias for :meth:`permit` kept for older SDK users."""
128
+ return cls.permit(
129
+ reasoning=reasoning,
130
+ policy_id=policy_id,
131
+ policy_name=policy_name,
132
+ policy_effect=policy_effect,
133
+ policy_decisions=policy_decisions,
134
+ )
135
+
136
+ @classmethod
137
+ def deny(
138
+ cls,
139
+ reasoning: str,
140
+ policy_id: str | None = None,
141
+ policy_name: str | None = None,
142
+ policy_effect: str | None = None,
143
+ policy_decisions: list[dict[str, str | None]] | None = None,
144
+ ) -> "Decision":
145
+ return cls(
146
+ effect=Effect.DENY,
147
+ reasoning=reasoning,
148
+ policy_id=policy_id,
149
+ policy_name=policy_name,
150
+ policy_effect=policy_effect,
151
+ policy_decisions=policy_decisions,
152
+ )
153
+
154
+ @classmethod
155
+ def modify(
156
+ cls,
157
+ reasoning: str,
158
+ modified_args: dict[str, object],
159
+ policy_id: str | None = None,
160
+ policy_name: str | None = None,
161
+ ) -> "Decision":
162
+ """Allow the action with rewritten arguments (AARM MODIFY)."""
163
+ return cls(
164
+ effect=Effect.MODIFY,
165
+ reasoning=reasoning,
166
+ policy_id=policy_id,
167
+ policy_name=policy_name,
168
+ modified_args=modified_args,
169
+ )
170
+
171
+ @classmethod
172
+ def redact(
173
+ cls,
174
+ reasoning: str,
175
+ policy_id: str | None = None,
176
+ policy_name: str | None = None,
177
+ policy_effect: str | None = None,
178
+ policy_decisions: list[dict[str, str | None]] | None = None,
179
+ ) -> "Decision":
180
+ """Narrower alias of :meth:`modify` emitted when PII / secrets were
181
+ redacted before the action ran. Preferred for backwards compatibility
182
+ with existing dashboards that filter by ``redact``.
183
+ """
184
+ return cls(
185
+ effect=Effect.REDACT,
186
+ reasoning=reasoning,
187
+ policy_id=policy_id,
188
+ policy_name=policy_name,
189
+ policy_effect=policy_effect,
190
+ policy_decisions=policy_decisions,
191
+ )
192
+
193
+ @classmethod
194
+ def step_up(
195
+ cls,
196
+ reasoning: str,
197
+ policy_id: str | None = None,
198
+ policy_name: str | None = None,
199
+ policy_effect: str | None = None,
200
+ policy_decisions: list[dict[str, str | None]] | None = None,
201
+ policy_timeout_behavior: str | None = None,
202
+ ) -> "Decision":
203
+ """Require human approval before the action runs (AARM STEP_UP)."""
204
+ return cls(
205
+ effect=Effect.STEP_UP,
206
+ reasoning=reasoning,
207
+ policy_id=policy_id,
208
+ policy_name=policy_name,
209
+ policy_effect=policy_effect,
210
+ policy_decisions=policy_decisions,
211
+ policy_timeout_behavior=policy_timeout_behavior,
212
+ )
213
+
214
+ @classmethod
215
+ def escalate(
216
+ cls,
217
+ reasoning: str,
218
+ policy_id: str | None = None,
219
+ policy_name: str | None = None,
220
+ policy_effect: str | None = None,
221
+ policy_decisions: list[dict[str, str | None]] | None = None,
222
+ policy_timeout_behavior: str | None = None,
223
+ ) -> "Decision":
224
+ """Legacy SDK factory. Identical to :meth:`step_up` but emits the
225
+ ``escalate`` effect so older dashboards keep filtering correctly."""
226
+ return cls(
227
+ effect=Effect.ESCALATE,
228
+ reasoning=reasoning,
229
+ policy_id=policy_id,
230
+ policy_name=policy_name,
231
+ policy_effect=policy_effect,
232
+ policy_decisions=policy_decisions,
233
+ policy_timeout_behavior=policy_timeout_behavior,
234
+ )
235
+
236
+ @classmethod
237
+ def defer(
238
+ cls,
239
+ reasoning: str,
240
+ policy_id: str | None = None,
241
+ policy_name: str | None = None,
242
+ ) -> "Decision":
243
+ """Suspend the decision pending more context (AARM DEFER)."""
244
+ return cls(
245
+ effect=Effect.DEFER,
246
+ reasoning=reasoning,
247
+ policy_id=policy_id,
248
+ policy_name=policy_name,
249
+ )
@@ -9,7 +9,7 @@ import math
9
9
  import os
10
10
  import time
11
11
  from datetime import datetime
12
- from decimal import Decimal, ROUND_HALF_UP
12
+ from decimal import ROUND_HALF_UP, Decimal
13
13
  from typing import Any
14
14
 
15
15
  import structlog
@@ -25,7 +25,7 @@ except Exception as exc:
25
25
  policies_dir="backend",
26
26
  ) from exc
27
27
 
28
- from cortexhub.policy.effects import Decision, Effect
28
+ from cortexhub.policy.effects import Decision
29
29
  from cortexhub.policy.loader import PolicyBundle
30
30
  from cortexhub.policy.models import AuthorizationRequest
31
31
 
@@ -153,17 +153,31 @@ class PolicyEvaluator:
153
153
  tool_name = resource_id # for tool.invoke, resource is the tool
154
154
 
155
155
  tool_policies = getattr(self.policy_bundle, "tool_policies", None) or {}
156
-
157
- # Per-tool bundle: only evaluate if this tool has active policies (v2: otherwise ungoverned → permit)
158
- if tool_policies:
159
- if tool_name not in tool_policies:
160
- return Decision.permit(
161
- f"No active policy for tool '{tool_name}' (ungoverned)",
162
- policy_id="ungoverned",
163
- policy_decisions=[],
164
- )
156
+ bucket_policies = getattr(self.policy_bundle, "bucket_policies", None) or {}
157
+ classifications = getattr(self.policy_bundle, "tool_classifications", None) or {}
158
+
159
+ # Resolution order on the SDK side mirrors the backend:
160
+ # 1. Tool-specific rule wins
161
+ # 2. Else look up the tool's (connector_id, bucket) and apply that bucket policy
162
+ # 3. Else ungoverned → permit
163
+ entry: dict[str, Any] | None = None
164
+ if tool_policies and tool_name in tool_policies and isinstance(tool_policies[tool_name], dict):
165
165
  entry = tool_policies[tool_name]
166
- if not isinstance(entry, dict):
166
+ elif bucket_policies:
167
+ cls = classifications.get(tool_name) if isinstance(classifications, dict) else None
168
+ if isinstance(cls, dict):
169
+ connector_id = cls.get("connector_id")
170
+ bucket = cls.get("bucket")
171
+ if connector_id and bucket:
172
+ bucket_key = f"{connector_id}::{bucket}"
173
+ candidate = bucket_policies.get(bucket_key)
174
+ if isinstance(candidate, dict):
175
+ entry = candidate
176
+
177
+ if tool_policies or bucket_policies:
178
+ # Per-tool / bucket mode — evaluate the resolved entry, or fall
179
+ # through to ungoverned if nothing matched.
180
+ if entry is None:
167
181
  return Decision.permit(
168
182
  f"No active policy for tool '{tool_name}' (ungoverned)",
169
183
  policy_id="ungoverned",
@@ -30,6 +30,8 @@ class PolicyBundle:
30
30
  schema: dict[str, Any],
31
31
  metadata: dict[str, Any],
32
32
  tool_policies: dict[str, dict[str, Any]] | None = None,
33
+ bucket_policies: dict[str, dict[str, Any]] | None = None,
34
+ tool_classifications: dict[str, dict[str, str | None]] | None = None,
33
35
  ):
34
36
  """Initialize policy bundle.
35
37
 
@@ -38,11 +40,18 @@ class PolicyBundle:
38
40
  schema: Policy schema dict (fallback when tool_policies not used)
39
41
  metadata: Bundle metadata (version, default_behavior, policy_map)
40
42
  tool_policies: Optional per-tool bundles: tool_name -> { "cedar", "schema", "policy_metadata" }
43
+ bucket_policies: Optional per-"(connector_id, bucket)" bundles,
44
+ keyed ``"<connector_id>::<bucket>"`` — same shape as tool_policies
45
+ entries. Lets one policy cover a whole connector at a time.
46
+ tool_classifications: tool_name → {bucket, risk, connector_id}.
47
+ Drives the bucket-policy lookup when a call has no tool-specific rule.
41
48
  """
42
49
  self.policies = policies
43
50
  self.schema = schema
44
51
  self.metadata = metadata
45
52
  self.tool_policies = tool_policies
53
+ self.bucket_policies = bucket_policies
54
+ self.tool_classifications = tool_classifications
46
55
  self.version = metadata.get("version", "unknown")
47
56
  self.default_behavior = metadata.get("default_behavior", "allow_and_log")
48
57
 
@@ -112,7 +121,17 @@ class PolicyLoader:
112
121
  with open(metadata_file) as f:
113
122
  metadata = json.load(f)
114
123
 
115
- bundle = PolicyBundle(policies=policies, schema=schema, metadata=metadata)
124
+ bucket_policies = metadata.get("bucket_policies") or None
125
+ tool_classifications = metadata.get("tool_classifications") or None
126
+ bundle = PolicyBundle(
127
+ policies=policies,
128
+ schema=schema,
129
+ metadata=metadata,
130
+ bucket_policies=bucket_policies if isinstance(bucket_policies, dict) else None,
131
+ tool_classifications=(
132
+ tool_classifications if isinstance(tool_classifications, dict) else None
133
+ ),
134
+ )
116
135
 
117
136
  logger.info(
118
137
  "Policy bundle loaded",
@@ -29,7 +29,7 @@ class PolicySync:
29
29
  3. SDK enforces policies locally
30
30
  4. No customer data involved in sync
31
31
  """
32
-
32
+
33
33
  def __init__(
34
34
  self,
35
35
  agent_key: str | None,
@@ -69,7 +69,7 @@ class PolicySync:
69
69
  # Auto-sync on init if enabled
70
70
  if auto_sync and agent_key:
71
71
  self.sync()
72
-
72
+
73
73
  def sync(self) -> bool:
74
74
  """Sync policies from cloud.
75
75
 
@@ -79,18 +79,18 @@ class PolicySync:
79
79
  if not self.agent_key or not self._client:
80
80
  logger.debug("No agent key — using local policies only")
81
81
  return False
82
-
82
+
83
83
  try:
84
84
  # Check for updates first (lightweight)
85
85
  current_version = self._get_remote_version()
86
-
86
+
87
87
  if current_version == self._last_sync_version:
88
88
  logger.debug("Policies up to date", version=current_version)
89
89
  return True
90
-
90
+
91
91
  # Download full bundle
92
92
  bundle = self._download_bundle()
93
-
93
+
94
94
  if bundle:
95
95
  self._save_bundle(bundle)
96
96
  self._last_sync_version = current_version
@@ -100,60 +100,60 @@ class PolicySync:
100
100
  policy_count=len(bundle.get("policies", [])),
101
101
  )
102
102
  return True
103
-
103
+
104
104
  return False
105
-
105
+
106
106
  except httpx.ConnectError:
107
107
  logger.warning("Backend unreachable - using local policies")
108
108
  return False
109
109
  except Exception as e:
110
110
  logger.error("Policy sync error", error=str(e))
111
111
  return False
112
-
112
+
113
113
  def _get_remote_version(self) -> str | None:
114
114
  """Get current policy bundle version from cloud."""
115
115
  if not self._client:
116
116
  return None
117
-
117
+
118
118
  try:
119
119
  response = self._client.get("/policies/version")
120
120
  if response.status_code == 200:
121
121
  return response.json().get("version")
122
122
  except Exception:
123
123
  pass
124
-
124
+
125
125
  return None
126
-
126
+
127
127
  def _download_bundle(self) -> dict[str, Any] | None:
128
128
  """Download full policy bundle from cloud."""
129
129
  if not self._client:
130
130
  return None
131
-
131
+
132
132
  try:
133
133
  response = self._client.get("/policies/bundle")
134
134
  if response.status_code == 200:
135
135
  return response.json()
136
136
  except Exception as e:
137
137
  logger.error("Failed to download policy bundle", error=str(e))
138
-
138
+
139
139
  return None
140
-
140
+
141
141
  def _save_bundle(self, bundle: dict[str, Any]) -> None:
142
142
  """Save policy bundle to local cache."""
143
143
  # Save policy source files
144
144
  cedar_dir = self.local_policies_dir / "cedar"
145
145
  cedar_dir.mkdir(parents=True, exist_ok=True)
146
-
146
+
147
147
  # Save main policies file
148
148
  policies_content = bundle.get("policies_cedar", "")
149
149
  if policies_content:
150
150
  (cedar_dir / "policies.cedar").write_text(policies_content)
151
-
151
+
152
152
  # Save schema
153
153
  schema = bundle.get("schema", {})
154
154
  if schema:
155
155
  (cedar_dir / "schema.json").write_text(json.dumps(schema, indent=2))
156
-
156
+
157
157
  # Build policy_map from the structured policies list.
158
158
  # The HTTP bundle endpoint does not include a pre-built policy_map —
159
159
  # it is derived locally so the statement index matches exactly.
@@ -178,6 +178,35 @@ class PolicySync:
178
178
  }
179
179
  cedar_index += 1
180
180
 
181
+ # Derive bucket_policies from the raw list so the offline path mirrors
182
+ # the online bundle (same resolution order).
183
+ bucket_policies: dict[str, Any] = {}
184
+ if isinstance(raw_policies, list):
185
+ for p in raw_policies:
186
+ if not isinstance(p, dict):
187
+ continue
188
+ mc = p.get("match_connector_id")
189
+ mb = p.get("match_bucket")
190
+ cedar_text = p.get("cedar_policy") or ""
191
+ if not (mc and mb and cedar_text):
192
+ continue
193
+ bucket_policies[f"{mc}::{mb}"] = {
194
+ "cedar": cedar_text,
195
+ "schema": None,
196
+ "policy_metadata": {
197
+ "policy0": {
198
+ "name": p.get("name"),
199
+ "effect": p.get("effect"),
200
+ "tool_name": None,
201
+ "policy_document_id": p.get("id"),
202
+ "approval_destination": p.get("approval_destination"),
203
+ "approval_webhook_id": p.get("approval_webhook_id"),
204
+ }
205
+ },
206
+ }
207
+
208
+ tool_classifications = bundle.get("tool_classifications") or {}
209
+
181
210
  # Save metadata
182
211
  _gov_agent = bundle.get("agent_id") or bundle.get("project_id")
183
212
  metadata = {
@@ -187,14 +216,16 @@ class PolicySync:
187
216
  "default_behavior": bundle.get("default_behavior", "allow_and_log"),
188
217
  "policy_map": policy_map,
189
218
  "agent_id": _gov_agent,
219
+ "bucket_policies": bucket_policies,
220
+ "tool_classifications": tool_classifications,
190
221
  }
191
222
  (self.local_policies_dir / "metadata.json").write_text(json.dumps(metadata, indent=2))
192
-
223
+
193
224
  logger.debug(
194
225
  "Policy bundle saved locally",
195
226
  path=str(self.local_policies_dir),
196
227
  )
197
-
228
+
198
229
  def get_local_version(self) -> str | None:
199
230
  """Get version of locally cached policies."""
200
231
  metadata_file = self.local_policies_dir / "metadata.json"
@@ -205,7 +236,7 @@ class PolicySync:
205
236
  except Exception:
206
237
  pass
207
238
  return None
208
-
239
+
209
240
  def close(self):
210
241
  """Close the HTTP client."""
211
242
  if self._client:
@@ -1,152 +0,0 @@
1
- """Decision effects from policy evaluation.
2
-
3
- Critical: Determinism guarantee - Same AuthorizationRequest MUST always produce
4
- same Decision. This is essential for testing and auditability.
5
- """
6
-
7
- from enum import Enum
8
-
9
- from pydantic import BaseModel
10
-
11
-
12
- class Effect(str, Enum):
13
- """Policy decision effect (v2: permit / deny / escalate in telemetry)."""
14
-
15
- PERMIT = "permit"
16
- DENY = "deny"
17
- ESCALATE = "escalate"
18
- REDACT = "redact" # PII/secrets were redacted before LLM call
19
-
20
-
21
- class Decision(BaseModel):
22
- """Result of policy evaluation.
23
-
24
- Attributes:
25
- effect: The decision (PERMIT/DENY/ESCALATE)
26
- reasoning: Human-readable explanation
27
- policy_id: Which policy triggered this decision (if any)
28
- policy_name: Friendly policy name (if available)
29
- policy_effect: Policy effect metadata (if available)
30
- policy_decisions: All matching policy decisions (if available)
31
- """
32
-
33
- effect: Effect
34
- reasoning: str
35
- policy_id: str | None = None
36
- policy_name: str | None = None
37
- policy_effect: str | None = None
38
- policy_decisions: list[dict[str, str | None]] | None = None
39
- # When approval expires or wait times out: "deny" (default) or "allow"
40
- policy_timeout_behavior: str | None = None
41
-
42
- def is_allowed(self) -> bool:
43
- """Check if the decision allows execution (permit)."""
44
- return self.effect == Effect.PERMIT
45
-
46
- def is_denied(self) -> bool:
47
- """Check if the decision denies execution."""
48
- return self.effect == Effect.DENY
49
-
50
- def requires_approval(self) -> bool:
51
- """Check if the decision requires approval (escalation)."""
52
- return self.effect == Effect.ESCALATE
53
-
54
- @classmethod
55
- def permit(
56
- cls,
57
- reasoning: str = "Permitted by policy",
58
- policy_id: str | None = None,
59
- policy_name: str | None = None,
60
- policy_effect: str | None = None,
61
- policy_decisions: list[dict[str, str | None]] | None = None,
62
- ):
63
- """Create a PERMIT decision."""
64
- return cls(
65
- effect=Effect.PERMIT,
66
- reasoning=reasoning,
67
- policy_id=policy_id,
68
- policy_name=policy_name,
69
- policy_effect=policy_effect,
70
- policy_decisions=policy_decisions,
71
- )
72
-
73
- @classmethod
74
- def allow(
75
- cls,
76
- reasoning: str = "Permitted by policy",
77
- policy_id: str | None = None,
78
- policy_name: str | None = None,
79
- policy_effect: str | None = None,
80
- policy_decisions: list[dict[str, str | None]] | None = None,
81
- ):
82
- """Deprecated alias for :meth:`permit` (same effect: ``permit``)."""
83
- return cls.permit(
84
- reasoning=reasoning,
85
- policy_id=policy_id,
86
- policy_name=policy_name,
87
- policy_effect=policy_effect,
88
- policy_decisions=policy_decisions,
89
- )
90
-
91
- @classmethod
92
- def deny(
93
- cls,
94
- reasoning: str,
95
- policy_id: str | None = None,
96
- policy_name: str | None = None,
97
- policy_effect: str | None = None,
98
- policy_decisions: list[dict[str, str | None]] | None = None,
99
- ):
100
- """Create a DENY decision."""
101
- return cls(
102
- effect=Effect.DENY,
103
- reasoning=reasoning,
104
- policy_id=policy_id,
105
- policy_name=policy_name,
106
- policy_effect=policy_effect,
107
- policy_decisions=policy_decisions,
108
- )
109
-
110
- @classmethod
111
- def escalate(
112
- cls,
113
- reasoning: str,
114
- policy_id: str | None = None,
115
- policy_name: str | None = None,
116
- policy_effect: str | None = None,
117
- policy_decisions: list[dict[str, str | None]] | None = None,
118
- policy_timeout_behavior: str | None = None,
119
- ):
120
- """Create an ESCALATE decision."""
121
- return cls(
122
- effect=Effect.ESCALATE,
123
- reasoning=reasoning,
124
- policy_id=policy_id,
125
- policy_name=policy_name,
126
- policy_effect=policy_effect,
127
- policy_decisions=policy_decisions,
128
- policy_timeout_behavior=policy_timeout_behavior,
129
- )
130
-
131
- @classmethod
132
- def redact(
133
- cls,
134
- reasoning: str,
135
- policy_id: str | None = None,
136
- policy_name: str | None = None,
137
- policy_effect: str | None = None,
138
- policy_decisions: list[dict[str, str | None]] | None = None,
139
- ):
140
- """Create a REDACT decision (PII/secrets were redacted before execution)."""
141
- return cls(
142
- effect=Effect.REDACT,
143
- reasoning=reasoning,
144
- policy_id=policy_id,
145
- policy_name=policy_name,
146
- policy_effect=policy_effect,
147
- policy_decisions=policy_decisions,
148
- )
149
-
150
- def is_redacted(self) -> bool:
151
- """Check if the decision resulted in redaction."""
152
- return self.effect == Effect.REDACT
File without changes
File without changes
File without changes