cortexhub 0.4.1__tar.gz → 0.5.0__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 (62) hide show
  1. {cortexhub-0.4.1 → cortexhub-0.5.0}/PKG-INFO +1 -1
  2. {cortexhub-0.4.1 → cortexhub-0.5.0}/pyproject.toml +1 -1
  3. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/backend/client.py +74 -10
  4. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/evaluator.py +26 -12
  5. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/loader.py +20 -1
  6. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/sync.py +52 -21
  7. {cortexhub-0.4.1 → cortexhub-0.5.0}/.gitignore +0 -0
  8. {cortexhub-0.4.1 → cortexhub-0.5.0}/LICENSE +0 -0
  9. {cortexhub-0.4.1 → cortexhub-0.5.0}/README.md +0 -0
  10. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/__init__.py +0 -0
  11. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/audit/__init__.py +0 -0
  12. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/audit/events.py +0 -0
  13. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/backend/__init__.py +0 -0
  14. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/client.py +0 -0
  15. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/config.py +0 -0
  16. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/constants.py +0 -0
  17. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/context/__init__.py +0 -0
  18. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/context/enricher.py +0 -0
  19. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/errors.py +0 -0
  20. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/__init__.py +0 -0
  21. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/injection.py +0 -0
  22. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/__init__.py +0 -0
  23. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSE +0 -0
  24. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSES_SOURCES +0 -0
  25. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/README.md +0 -0
  26. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/accuracy.json +0 -0
  27. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/attribute_ruler/patterns +0 -0
  28. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/config.cfg +0 -0
  29. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/lemmatizer/lookups/lookups.bin +0 -0
  30. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/meta.json +0 -0
  31. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/cfg +0 -0
  32. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/model +0 -0
  33. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/moves +0 -0
  34. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/cfg +0 -0
  35. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/model +0 -0
  36. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/moves +0 -0
  37. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/cfg +0 -0
  38. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/model +0 -0
  39. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/cfg +0 -0
  40. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/model +0 -0
  41. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/cfg +0 -0
  42. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/model +0 -0
  43. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tokenizer +0 -0
  44. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/key2row +0 -0
  45. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/lookups.bin +0 -0
  46. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/strings.json +0 -0
  47. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors +0 -0
  48. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors.cfg +0 -0
  49. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/models/en_core_web_sm/meta.json +0 -0
  50. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/pii.py +0 -0
  51. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/guardrails/secrets.py +0 -0
  52. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/interceptors/__init__.py +0 -0
  53. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/interceptors/mcp.py +0 -0
  54. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/logging.py +0 -0
  55. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/__init__.py +0 -0
  56. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/effects.py +0 -0
  57. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/policy/models.py +0 -0
  58. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/signing.py +0 -0
  59. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/telemetry/__init__.py +0 -0
  60. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/telemetry/otel.py +0 -0
  61. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/tool.py +0 -0
  62. {cortexhub-0.4.1 → cortexhub-0.5.0}/src/cortexhub/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cortexhub
3
- Version: 0.4.1
3
+ Version: 0.5.0
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.1"
3
+ version = "0.5.0"
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,11 +2,11 @@
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
 
@@ -51,12 +51,23 @@ class PolicyBundle:
51
51
  - "off" : send raw data (dev/staging only)
52
52
 
53
53
  tool_policies: when present, SDK evaluates only the policies for the tool being invoked.
54
+
55
+ tool_classifications: connector-classifier output (bucket + risk) per tool,
56
+ used to match bucket-scoped policies. When a tool doesn't have a
57
+ tool-specific rule, the SDK falls back to the bucket policy for its
58
+ (connector_id, bucket). Keyed by tool name.
59
+
60
+ bucket_policies: bucket-scoped rules keyed by "<connector_id>::<bucket>".
61
+ Same shape as tool_policies entries (cedar/schema/policy_metadata).
54
62
  """
55
63
  version: str
56
64
  policies: str # Policy source text (empty when using per-tool bundles only)
57
65
  schema: dict[str, Any] | None = None # Merged schema when tool_policies not used
58
66
  policy_metadata: dict[str, dict[str, Any]] | None = None
59
67
  tool_policies: dict[str, dict[str, Any]] | None = None
68
+ # Bucket policies + classifications for SDK-side bucket match.
69
+ bucket_policies: dict[str, dict[str, Any]] | None = None
70
+ tool_classifications: dict[str, dict[str, str | None]] | None = None
60
71
  guardrail_configs: dict[str, GuardrailConfig] | None = None
61
72
  policy_defaults: dict[str, Any] | None = None
62
73
  policy_packs: list[dict[str, Any]] | None = None
@@ -134,7 +145,7 @@ class BackendClient:
134
145
  """
135
146
  if not self.agent_key or not self._client:
136
147
  return False, None
137
-
148
+
138
149
  try:
139
150
  # Note: base_url already includes /v1, so just /api-keys/validate.
140
151
  payload: dict[str, str] = {}
@@ -148,7 +159,7 @@ class BackendClient:
148
159
  json=payload if payload else None,
149
160
  timeout=5.0,
150
161
  )
151
-
162
+
152
163
  if response.status_code == 200:
153
164
  try:
154
165
  data = response.json()
@@ -160,12 +171,12 @@ class BackendClient:
160
171
  error=str(parse_err),
161
172
  )
162
173
  return False, None
163
-
174
+
164
175
  # Check if valid
165
176
  if not data.get("valid", False):
166
177
  logger.warning("Agent key validation failed", message=data.get("message"))
167
178
  return False, None
168
-
179
+
169
180
  # Parse policy bundle from backend
170
181
  # Backend returns: { policies: { version, policies: [...], privacy_mode }, guardrail_config?: {...} }
171
182
  # Guardrails are project-level only (validate returns guardrail_config when enabled).
@@ -248,7 +259,7 @@ class BackendClient:
248
259
  else:
249
260
  policies_str = raw_policies or ""
250
261
  policy_map = {}
251
-
262
+
252
263
  # Per-tool policies (preferred): backend sends tool_policies when available
253
264
  raw_tool_policies = policies_data.get("tool_policies")
254
265
  tool_policies: dict[str, dict[str, Any]] | None = None
@@ -262,6 +273,57 @@ class BackendClient:
262
273
  for k, v in raw_tool_policies.items()
263
274
  }
264
275
 
276
+ # Bucket-scoped policies: build per-(connector, bucket) entry
277
+ # from the raw policies list by inspecting match_connector_id /
278
+ # match_bucket. The same validate endpoint returns this shape
279
+ # when the control plane has connector-scoped policies.
280
+ bucket_policies: dict[str, dict[str, Any]] | None = None
281
+ raw_flat_policies = policies_data.get("policies") or []
282
+ if isinstance(raw_flat_policies, list):
283
+ bucket_acc: dict[str, dict[str, Any]] = {}
284
+ for p in raw_flat_policies:
285
+ if not isinstance(p, dict):
286
+ continue
287
+ mc = p.get("match_connector_id")
288
+ mb = p.get("match_bucket")
289
+ cedar_text = p.get("cedar_policy") or ""
290
+ if not (mc and mb and cedar_text):
291
+ continue
292
+ key = f"{mc}::{mb}"
293
+ bucket_acc[key] = {
294
+ "cedar": cedar_text,
295
+ "schema": None,
296
+ "policy_metadata": {
297
+ "policy0": {
298
+ "name": p.get("name"),
299
+ "effect": p.get("effect"),
300
+ "tool_name": None,
301
+ "policy_document_id": p.get("id"),
302
+ "approval_destination": p.get("approval_destination"),
303
+ "approval_webhook_id": p.get("approval_webhook_id"),
304
+ "approval_timeout_behavior": (
305
+ p.get("approval_timeout_behavior") or "deny"
306
+ ).lower(),
307
+ }
308
+ },
309
+ }
310
+ bucket_policies = bucket_acc or None
311
+
312
+ # Classification map: {tool_name → {bucket, risk, connector_id}}
313
+ raw_classifications = policies_data.get("tool_classifications")
314
+ tool_classifications: dict[str, dict[str, str | None]] | None = None
315
+ if isinstance(raw_classifications, dict) and raw_classifications:
316
+ tool_classifications = {
317
+ str(k): {
318
+ "bucket": (v.get("bucket") if isinstance(v, dict) else None),
319
+ "risk": (v.get("risk") if isinstance(v, dict) else None),
320
+ "connector_id": (
321
+ v.get("connector_id") if isinstance(v, dict) else None
322
+ ),
323
+ }
324
+ for k, v in raw_classifications.items()
325
+ }
326
+
265
327
  # privacy_mode may be in policies object or at top level (defensive)
266
328
  _privacy = policies_data.get("privacy_mode") or data.get("privacy_mode") or "on"
267
329
  policies = PolicyBundle(
@@ -270,6 +332,8 @@ class BackendClient:
270
332
  schema=policies_data.get("schema"),
271
333
  policy_metadata=policy_map,
272
334
  tool_policies=tool_policies,
335
+ bucket_policies=bucket_policies,
336
+ tool_classifications=tool_classifications,
273
337
  guardrail_configs=guardrail_configs if guardrail_configs else None,
274
338
  policy_defaults=policies_data.get("policy_defaults"),
275
339
  policy_packs=policies_data.get("policy_packs"),
@@ -278,7 +342,7 @@ class BackendClient:
278
342
  privacy_mode=_privacy,
279
343
  )
280
344
  logger.debug("Validate response privacy_mode", privacy_mode=_privacy)
281
-
345
+
282
346
  _aid = data.get("agent_id") or data.get("project_id") or ""
283
347
  _gid = data.get("group_id")
284
348
  config = SDKConfig(
@@ -332,7 +396,7 @@ class BackendClient:
332
396
  except Exception as e:
333
397
  logger.error("Agent key validation error", error=str(e))
334
398
  return False, None
335
-
399
+
336
400
  def close(self):
337
401
  """Close the HTTP client."""
338
402
  if self._client:
@@ -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:
File without changes
File without changes
File without changes