integrity-killswitch 0.3.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.
@@ -0,0 +1,477 @@
1
+ """Cloud Control Plane PANIC sync & local cache for agent-killswitch (stdlib only).
2
+
3
+ Polls `GET <cloud_url>/api/v1/killswitch/state` with `Authorization: Bearer <key>`
4
+ and caches the remote killswitch policy locally. If remote `master_panic` is true,
5
+ immediately latches local `state.json` (fail-safe tighten-only) so Dashboard's
6
+ Big Red PANIC button genuinely halts local agents even if the host goes offline.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from collections.abc import Callable
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ DEFAULT_CLOUD_URL = "https://integrity.subnet.zp.ua"
23
+ DEFAULT_CLOUD_TIMEOUT = 3.0
24
+ DEFAULT_CLOUD_TTL = 15.0
25
+ DEFAULT_CLOUD_BACKOFF = 30.0
26
+ MAX_CLOUD_RESPONSE_BYTES = 1024 * 1024
27
+ USER_AGENT = "integrity-harness-cli/1.2"
28
+ CLOUD_CACHE_SCHEMA = "agent-killswitch-cloud-cache/v1"
29
+
30
+ CloudFetcher = Callable[[str, str, float], dict[str, Any]]
31
+
32
+
33
+ class CorruptCloudCacheError(ValueError):
34
+ """Raised when an existing cloud_cache.json file is corrupt or malformed."""
35
+
36
+
37
+ def _utc_now() -> str:
38
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
39
+
40
+
41
+ def resolve_cloud_url(cloud_url: str | None = None, *, default_if_empty: bool = False) -> str | None:
42
+ """Resolves cloud base URL from CLI argument, `INTEGRITY_CLOUD_URL`, or `INTEGRITY_BASE_URL`."""
43
+ raw = (
44
+ cloud_url
45
+ or os.environ.get("INTEGRITY_CLOUD_URL")
46
+ or os.environ.get("INTEGRITY_BASE_URL")
47
+ or ""
48
+ ).strip()
49
+ if not raw:
50
+ return DEFAULT_CLOUD_URL if default_if_empty else None
51
+ clean = raw.rstrip("/")
52
+ if not (clean.startswith("https://") or clean.startswith("http://")):
53
+ raise ValueError("Cloud URL must start with https:// or http://")
54
+ return clean
55
+
56
+
57
+ def resolve_license_key(license_key: str | None = None) -> str | None:
58
+ """Resolves API license key from CLI argument or `INTEGRITY_LICENSE_KEY`."""
59
+ raw = (license_key or os.environ.get("INTEGRITY_LICENSE_KEY") or "").strip()
60
+ return raw or None
61
+
62
+
63
+ def resolve_cloud_ttl(ttl: float | None = None) -> float:
64
+ """Resolves cache TTL in seconds from argument or `INTEGRITY_CLOUD_TTL` (default 15s)."""
65
+ if ttl is not None:
66
+ return max(0.0, float(ttl))
67
+ raw = (os.environ.get("INTEGRITY_CLOUD_TTL") or "").strip()
68
+ if not raw:
69
+ return DEFAULT_CLOUD_TTL
70
+ try:
71
+ return max(0.0, float(raw))
72
+ except ValueError:
73
+ return DEFAULT_CLOUD_TTL
74
+
75
+
76
+ def resolve_cloud_backoff(backoff: float | None = None) -> float:
77
+ """Resolves negative-cache backoff in seconds from argument or `INTEGRITY_CLOUD_BACKOFF` (default 30s)."""
78
+ if backoff is not None:
79
+ return max(0.0, float(backoff))
80
+ raw = (os.environ.get("INTEGRITY_CLOUD_BACKOFF") or "").strip()
81
+ if not raw:
82
+ return DEFAULT_CLOUD_BACKOFF
83
+ try:
84
+ return max(0.0, float(raw))
85
+ except ValueError:
86
+ return DEFAULT_CLOUD_BACKOFF
87
+
88
+
89
+ def cloud_cache_path(state_file: Path) -> Path:
90
+ """Returns local cache file path for cloud killswitch state."""
91
+ override = (os.environ.get("AGENT_KILLSWITCH_CLOUD_CACHE") or "").strip()
92
+ if override:
93
+ return Path(override)
94
+ return state_file.with_name("cloud_cache.json")
95
+
96
+
97
+ def _fallback_cache_path() -> Path:
98
+ return Path.home() / ".agent-killswitch" / "cloud_cache.json"
99
+
100
+
101
+ def _is_valid_cache_payload(data: Any) -> bool:
102
+ if not isinstance(data, dict):
103
+ return False
104
+ state = data.get("state")
105
+ if isinstance(state, dict):
106
+ return True
107
+ return state is None and isinstance(data.get("last_error_utc"), str)
108
+
109
+
110
+ def load_cloud_cache(state_file: Path, *, raise_on_corrupt: bool = False) -> dict[str, Any] | None:
111
+ """Reads cached remote killswitch state if present and valid.
112
+
113
+ Emits an explicit stderr warning if an existing cache file is corrupt or malformed,
114
+ and raises `CorruptCloudCacheError` when `raise_on_corrupt=True`.
115
+ """
116
+ from . import core
117
+
118
+ primary = cloud_cache_path(state_file)
119
+ candidates = [primary]
120
+ # Only fall back to ~/.agent-killswitch/cloud_cache.json when state_file lives
121
+ # in a hardened read-only directory (e.g. /etc/agent-killswitch or ProgramData).
122
+ if not (primary.parent.exists() and os.access(primary.parent, os.W_OK)):
123
+ fallback = _fallback_cache_path()
124
+ if fallback not in candidates:
125
+ candidates.append(fallback)
126
+ corrupt_exc: CorruptCloudCacheError | None = None
127
+ for path in candidates:
128
+ if not path.is_file():
129
+ continue
130
+ try:
131
+ raw_text = core._read_text_retry(path)
132
+ except OSError as exc:
133
+ print(f"agent-killswitch: warning: unreadable cloud cache at {path}: {exc}", file=sys.stderr)
134
+ corrupt_exc = CorruptCloudCacheError(f"Unreadable cloud cache at {path}: {exc}")
135
+ continue
136
+ try:
137
+ data = json.loads(raw_text)
138
+ except ValueError as exc:
139
+ print(f"agent-killswitch: warning: corrupt cloud cache at {path}: {exc}", file=sys.stderr)
140
+ corrupt_exc = CorruptCloudCacheError(f"Corrupt JSON in cloud cache at {path}: {exc}")
141
+ continue
142
+ if _is_valid_cache_payload(data):
143
+ return data
144
+ print(
145
+ f"agent-killswitch: warning: malformed cloud cache at {path}: missing valid 'state' or backoff metadata",
146
+ file=sys.stderr,
147
+ )
148
+ corrupt_exc = CorruptCloudCacheError(f"Malformed cloud cache at {path}")
149
+ if raise_on_corrupt and corrupt_exc is not None:
150
+ raise corrupt_exc
151
+ return None
152
+
153
+
154
+ def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
155
+ from . import core
156
+
157
+ with core.state_lock(path):
158
+ core._write_json_atomic(path, data)
159
+
160
+
161
+ def save_cloud_cache(state_file: Path, payload: dict[str, Any]) -> Path | None:
162
+ """Atomically writes cloud cache next to state_file (or ~/.agent-killswitch if read-only)."""
163
+ primary = cloud_cache_path(state_file)
164
+ try:
165
+ _atomic_write_json(primary, payload)
166
+ return primary
167
+ except OSError:
168
+ fallback = _fallback_cache_path()
169
+ if fallback == primary:
170
+ return None
171
+ try:
172
+ _atomic_write_json(fallback, payload)
173
+ return fallback
174
+ except OSError:
175
+ return None
176
+
177
+
178
+ def normalize_remote_state(raw_payload: dict[str, Any]) -> tuple[dict[str, Any], str | None]:
179
+ """Extracts normalized killswitch state dict and optional tenant_id from cloud API JSON."""
180
+ tenant_id = raw_payload.get("tenant_id")
181
+ inner = raw_payload.get("state") if isinstance(raw_payload.get("state"), dict) else raw_payload
182
+ if not isinstance(inner, dict):
183
+ raise ValueError("Cloud killswitch response missing 'state' object")
184
+ disabled_vendors = inner.get("disabled_vendors") or []
185
+ disabled_scopes = inner.get("disabled_scopes") or []
186
+ if not isinstance(disabled_vendors, list) or not isinstance(disabled_scopes, list):
187
+ raise ValueError("Cloud killswitch disabled_vendors/disabled_scopes must be lists")
188
+ raw_version = inner.get("version")
189
+ if isinstance(raw_version, bool) or raw_version is None:
190
+ version = 0
191
+ else:
192
+ try:
193
+ version = int(raw_version)
194
+ except (TypeError, ValueError):
195
+ version = 0
196
+ normalized = {
197
+ "schema": str(inner.get("schema") or "integrity-fleet-killswitch/v1"),
198
+ "version": version,
199
+ "master_panic": inner.get("master_panic", False) is True,
200
+ "reason": str(inner.get("reason") or ""),
201
+ "disabled_vendors": sorted({str(v).strip().lower() for v in disabled_vendors if str(v).strip()}),
202
+ "disabled_scopes": sorted({str(s).strip().lower() for s in disabled_scopes if str(s).strip()}),
203
+ "updated_utc": inner.get("updated_utc"),
204
+ "updated_by": inner.get("updated_by"),
205
+ }
206
+ return normalized, (str(tenant_id) if tenant_id is not None else None)
207
+
208
+
209
+ def _extract_raw_socket(resp: Any) -> Any | None:
210
+ fp = getattr(resp, "fp", None)
211
+ raw = getattr(fp, "raw", None)
212
+ sock = getattr(raw, "_sock", None)
213
+ if sock is not None and hasattr(sock, "settimeout"):
214
+ return sock
215
+ sock = getattr(fp, "_sock", None)
216
+ if sock is not None and hasattr(sock, "settimeout"):
217
+ return sock
218
+ return None
219
+
220
+
221
+ def default_cloud_fetcher(
222
+ cloud_url: str,
223
+ license_key: str,
224
+ timeout: float = DEFAULT_CLOUD_TIMEOUT,
225
+ ) -> dict[str, Any]:
226
+ """Fetches `GET <cloud_url>/api/v1/killswitch/state` using stdlib `urllib.request`.
227
+
228
+ Enforces a strict total wall-clock deadline across connection + chunk reads
229
+ so slow-trickle responses cannot stall hook hot paths.
230
+ """
231
+ endpoint = f"{cloud_url.rstrip('/')}/api/v1/killswitch/state"
232
+ if not (endpoint.startswith("https://") or endpoint.startswith("http://")):
233
+ raise ValueError("Cloud endpoint must use http:// or https://")
234
+ total_timeout = max(0.01, float(timeout))
235
+ deadline = time.monotonic() + total_timeout
236
+ req = urllib.request.Request( # noqa: S310
237
+ endpoint,
238
+ method="GET",
239
+ headers={
240
+ "Authorization": f"Bearer {license_key}",
241
+ "User-Agent": USER_AGENT,
242
+ "Accept": "application/json",
243
+ },
244
+ )
245
+ with urllib.request.urlopen(req, timeout=total_timeout) as resp: # noqa: S310
246
+ raw_sock = _extract_raw_socket(resp)
247
+ chunks: list[bytes] = []
248
+ total_bytes = 0
249
+ read_chunk = getattr(resp, "read1", None) or resp.read
250
+ while True:
251
+ remaining = deadline - time.monotonic()
252
+ if remaining <= 0:
253
+ raise TimeoutError(f"Cloud killswitch fetch exceeded {total_timeout:.2f}s wall-clock deadline")
254
+ if raw_sock is not None:
255
+ try:
256
+ raw_sock.settimeout(remaining)
257
+ except OSError:
258
+ pass
259
+ try:
260
+ chunk = read_chunk(8192)
261
+ except TypeError:
262
+ chunk = resp.read()
263
+ if chunk:
264
+ total_bytes += len(chunk)
265
+ if total_bytes > MAX_CLOUD_RESPONSE_BYTES:
266
+ raise ValueError("Cloud killswitch response exceeded maximum allowed size") from None
267
+ chunks.append(chunk)
268
+ break
269
+ if not chunk:
270
+ break
271
+ total_bytes += len(chunk)
272
+ if total_bytes > MAX_CLOUD_RESPONSE_BYTES:
273
+ raise ValueError("Cloud killswitch response exceeded maximum allowed size")
274
+ chunks.append(chunk)
275
+ if time.monotonic() >= deadline:
276
+ raise TimeoutError(f"Cloud killswitch fetch exceeded {total_timeout:.2f}s wall-clock deadline")
277
+ body = b"".join(chunks).decode("utf-8", errors="replace")
278
+ parsed = json.loads(body)
279
+ if not isinstance(parsed, dict):
280
+ raise ValueError("Cloud killswitch response must be a JSON object")
281
+ if parsed.get("ok") is False:
282
+ raise RuntimeError(str(parsed.get("error") or "Cloud killswitch API returned ok=false"))
283
+ return parsed
284
+
285
+
286
+ def _latch_local_panic(state_file: Path, reason: str) -> bool:
287
+ """Best-effort local fail-safe panic latch when remote master_panic is active."""
288
+ from . import core
289
+
290
+ note = f"Cloud PANIC latched: {reason}" if reason else "Cloud PANIC latched from Control Plane"
291
+ changed = False
292
+
293
+ def _apply_latch(local: dict[str, Any]) -> bool:
294
+ nonlocal changed
295
+ if not local.get("master_panic", False) or local.get("note") != note:
296
+ local["master_panic"] = True
297
+ local["note"] = note
298
+ changed = True
299
+ return True
300
+ return False
301
+
302
+ try:
303
+ core.mutate_state(state_file, _apply_latch, actor="cloud-sync")
304
+ if changed:
305
+ core.log_audit_event(
306
+ "cloud_panic_latched",
307
+ {"reason": note, "state_file": str(state_file)},
308
+ )
309
+ return True
310
+ except (OSError, TimeoutError):
311
+ return False
312
+
313
+
314
+ def sync_cloud_state(
315
+ *,
316
+ state_file: Path,
317
+ cloud_url: str | None = None,
318
+ license_key: str | None = None,
319
+ ttl: float | None = None,
320
+ backoff: float | None = None,
321
+ force: bool = False,
322
+ timeout: float = DEFAULT_CLOUD_TIMEOUT,
323
+ fetcher: CloudFetcher | None = None,
324
+ now_fn: Callable[[], float] = time.time,
325
+ ) -> dict[str, Any]:
326
+ """Synchronizes remote killswitch state with TTL caching, negative-cache backoff, and offline fallback.
327
+
328
+ Never persists or returns the license key.
329
+ """
330
+ active_fetcher = fetcher or default_cloud_fetcher
331
+ resolved_key = resolve_license_key(license_key)
332
+ resolved_url = resolve_cloud_url(cloud_url, default_if_empty=bool(resolved_key))
333
+ effective_ttl = resolve_cloud_ttl(ttl)
334
+ effective_backoff = resolve_cloud_backoff(backoff)
335
+ cached = load_cloud_cache(state_file)
336
+ cached_state = cached.get("state") if isinstance(cached, dict) and isinstance(cached.get("state"), dict) else None
337
+ now = now_fn()
338
+
339
+ if not resolved_url or not resolved_key:
340
+ return {
341
+ "configured": False,
342
+ "ok": False,
343
+ "online": False,
344
+ "from_cache": cached_state is not None,
345
+ "cloud_url": resolved_url,
346
+ "state": cached_state,
347
+ "latched_local_panic": False,
348
+ "error": "Cloud sync requires license key (INTEGRITY_LICENSE_KEY or --license-key).",
349
+ }
350
+
351
+ if (
352
+ not force
353
+ and cached is not None
354
+ and cached_state is not None
355
+ and cached.get("cloud_url") == resolved_url
356
+ and isinstance(cached.get("fetched_at"), (int, float))
357
+ and (now - float(cached["fetched_at"])) < effective_ttl
358
+ ):
359
+ latched = False
360
+ if cached_state.get("master_panic") is True:
361
+ latched = _latch_local_panic(state_file, str(cached_state.get("reason") or ""))
362
+ return {
363
+ "configured": True,
364
+ "ok": True,
365
+ "online": False,
366
+ "from_cache": True,
367
+ "cloud_url": resolved_url,
368
+ "tenant_id": cached.get("tenant_id"),
369
+ "state": cached_state,
370
+ "latched_local_panic": latched,
371
+ "error": None,
372
+ }
373
+
374
+ if (
375
+ not force
376
+ and cached is not None
377
+ and cached.get("cloud_url") == resolved_url
378
+ and effective_backoff > 0
379
+ and isinstance(cached.get("last_error_at"), (int, float))
380
+ and float(cached["last_error_at"]) >= float(cached.get("fetched_at") or 0.0)
381
+ and (now - float(cached["last_error_at"])) < effective_backoff
382
+ ):
383
+ latched = False
384
+ if cached_state and cached_state.get("master_panic") is True:
385
+ latched = _latch_local_panic(state_file, str(cached_state.get("reason") or ""))
386
+ return {
387
+ "configured": True,
388
+ "ok": False,
389
+ "online": False,
390
+ "from_cache": cached_state is not None,
391
+ "backoff_active": True,
392
+ "cloud_url": resolved_url,
393
+ "tenant_id": cached.get("tenant_id"),
394
+ "state": cached_state,
395
+ "latched_local_panic": latched,
396
+ "error": str(cached.get("last_error") or "Cloud backoff active"),
397
+ }
398
+
399
+ try:
400
+ raw = active_fetcher(resolved_url, resolved_key, timeout)
401
+ remote_state, tenant_id = normalize_remote_state(raw)
402
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError, RuntimeError) as exc:
403
+ err_msg = f"{type(exc).__name__}: {exc}"
404
+ same_url = cached is not None and cached.get("cloud_url") == resolved_url
405
+ neg_payload: dict[str, Any] = {
406
+ "schema": CLOUD_CACHE_SCHEMA,
407
+ "cloud_url": resolved_url,
408
+ "tenant_id": cached.get("tenant_id") if same_url else None,
409
+ "fetched_at": cached.get("fetched_at") if same_url else None,
410
+ "fetched_utc": cached.get("fetched_utc") if same_url else None,
411
+ "state": cached_state if same_url else None,
412
+ "last_error_at": now,
413
+ "last_error_utc": _utc_now(),
414
+ "last_error": err_msg,
415
+ }
416
+ save_cloud_cache(state_file, neg_payload)
417
+ latched = False
418
+ if cached_state and cached_state.get("master_panic") is True:
419
+ latched = _latch_local_panic(state_file, str(cached_state.get("reason") or ""))
420
+ return {
421
+ "configured": True,
422
+ "ok": False,
423
+ "online": False,
424
+ "from_cache": cached_state is not None,
425
+ "cloud_url": resolved_url,
426
+ "tenant_id": cached.get("tenant_id") if cached else None,
427
+ "state": cached_state,
428
+ "latched_local_panic": latched,
429
+ "error": err_msg,
430
+ }
431
+
432
+ cache_payload = {
433
+ "schema": CLOUD_CACHE_SCHEMA,
434
+ "cloud_url": resolved_url,
435
+ "tenant_id": tenant_id,
436
+ "fetched_at": now,
437
+ "fetched_utc": _utc_now(),
438
+ "state": remote_state,
439
+ }
440
+ cache_written = save_cloud_cache(state_file, cache_payload)
441
+ latched = False
442
+ if remote_state.get("master_panic") is True:
443
+ latched = _latch_local_panic(state_file, str(remote_state.get("reason") or ""))
444
+
445
+ return {
446
+ "configured": True,
447
+ "ok": True,
448
+ "online": True,
449
+ "from_cache": False,
450
+ "cloud_url": resolved_url,
451
+ "tenant_id": tenant_id,
452
+ "cache_file": str(cache_written) if cache_written else None,
453
+ "state": remote_state,
454
+ "latched_local_panic": latched,
455
+ "error": None,
456
+ }
457
+
458
+
459
+ def evaluate_cloud_state(
460
+ *,
461
+ detected_vendor: str,
462
+ action: str,
463
+ cloud_state: dict[str, Any] | None,
464
+ ) -> tuple[bool, str | None]:
465
+ """Evaluates cached/remote cloud policy against the caller vendor and action scope."""
466
+ if not cloud_state or detected_vendor == "owner":
467
+ return True, None
468
+ if cloud_state.get("master_panic") is True:
469
+ reason_detail = str(cloud_state.get("reason") or "Fleet panic active").strip()
470
+ return False, f"CLOUD MASTER PANIC ACTIVE: all AI agent access is blocked ({reason_detail})"
471
+ disabled_vendors = {str(v).strip().lower() for v in cloud_state.get("disabled_vendors") or []}
472
+ if detected_vendor in disabled_vendors:
473
+ return False, f"CLOUD KILLSWITCH OFF: access for vendor '{detected_vendor}' is disabled remotely"
474
+ disabled_scopes = {str(s).strip().lower() for s in cloud_state.get("disabled_scopes") or []}
475
+ if action and action != "any" and action.lower() in disabled_scopes:
476
+ return False, f"CLOUD SCOPE DISABLED: scope '{action}' is disabled remotely for all agents"
477
+ return True, None