piton-cli 0.4.2__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,500 @@
1
+ """
2
+ Persistent SQLite Control Plane Store for:
3
+ - MCP 2026-07-28 MRTR Human-in-the-Loop Escalations & Cryptographic Approval Signing
4
+ - Multi-Pod Signed Decision Ledger Ingestion (with Go<->Python HMAC verification)
5
+ - Live MCP Lockfile Drift Alerting
6
+ - Per-Agent `shadow -> enforce` Readiness Scorecards & Signed Compliance Bundles
7
+ """
8
+
9
+ import base64
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import sqlite3
14
+ import threading
15
+ import time
16
+ import uuid
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ from piton.iac.schema import normalize_json_numbers
21
+
22
+
23
+ def _hmac_hex(key: bytes, payload: bytes, length: int = 0) -> str:
24
+ digest = hmac.new(key, payload, hashlib.sha256).hexdigest()
25
+ return digest[:length] if length > 0 else digest
26
+
27
+
28
+ def verify_and_decode_mrtr_state(request_state: str, signing_key: bytes) -> Optional[Dict[str, Any]]:
29
+ """
30
+ Verifies a Go-minted MCP MRTR `requestState` (`base64url_nopad(json).hmac32`)
31
+ using constant-time HMAC-SHA256 verification and returns the decoded payload dict.
32
+ """
33
+ parts = request_state.strip().split(".")
34
+ if len(parts) != 2:
35
+ return None
36
+ b64_payload, sig = parts
37
+ pad = "=" * ((4 - len(b64_payload) % 4) % 4)
38
+ try:
39
+ raw = base64.urlsafe_b64decode(b64_payload + pad)
40
+ except Exception:
41
+ return None
42
+ expected = _hmac_hex(signing_key, raw, 32)
43
+ if not hmac.compare_digest(sig, expected):
44
+ return None
45
+ try:
46
+ data = json.loads(raw.decode("utf-8"))
47
+ except Exception:
48
+ return None
49
+ if not isinstance(data, dict):
50
+ return None
51
+ return data
52
+
53
+
54
+ def mint_approved_mrtr_token(request_state: str, signing_key: bytes) -> Tuple[Optional[str], Optional[str]]:
55
+ """
56
+ Cryptographically verifies an incoming MRTR `requestState`, ensures it has not
57
+ expired, flips `approved: true`, and returns a freshly signed `X-Piton-MRTR-Approval`
58
+ token accepted by the Go Envoy `ext_proc` and HTTP `/mcp/` sidecars.
59
+ """
60
+ payload = verify_and_decode_mrtr_state(request_state, signing_key)
61
+ if payload is None:
62
+ return None, "Invalid or tampered MRTR requestState signature."
63
+ expires_at = int(payload.get("expires_at") or 0)
64
+ if expires_at > 0 and time.time() > expires_at:
65
+ return None, "MRTR requestState has expired."
66
+
67
+ payload["approved"] = True
68
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
69
+ mac = _hmac_hex(signing_key, raw, 32)
70
+ token = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + "." + mac
71
+ return token, None
72
+
73
+
74
+ def verify_decision_record_hmac(record: Dict[str, Any], signing_key: bytes) -> bool:
75
+ """Verifies a Go/Python DecisionLedgerRecord HMAC-SHA256 signature."""
76
+ provided = str(record.get("record_hmac") or "")
77
+ if not provided:
78
+ return False
79
+ body = {k: v for k, v in record.items() if k != "record_hmac"}
80
+ normalized = normalize_json_numbers(body)
81
+ canonical = json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode("utf-8")
82
+ expected = _hmac_hex(signing_key, canonical)
83
+ return hmac.compare_digest(provided, expected)
84
+
85
+
86
+ def verify_slack_signature(
87
+ signing_secret: str,
88
+ timestamp: str,
89
+ raw_body: bytes,
90
+ provided_signature: str,
91
+ max_skew_seconds: int = 300,
92
+ ) -> bool:
93
+ """Verifies Slack webhook interactive callback `X-Slack-Signature` (v0=HMAC-SHA256)."""
94
+ if not signing_secret or not timestamp or not provided_signature:
95
+ return False
96
+ try:
97
+ ts_int = int(timestamp)
98
+ except ValueError:
99
+ return False
100
+ if abs(time.time() - ts_int) > max_skew_seconds:
101
+ return False
102
+ base = f"v0:{timestamp}:".encode("utf-8") + raw_body
103
+ expected = "v0=" + hmac.new(signing_secret.encode("utf-8"), base, hashlib.sha256).hexdigest()
104
+ return hmac.compare_digest(provided_signature.strip(), expected)
105
+
106
+
107
+ def build_slack_mrtr_blocks(escalation: Dict[str, Any]) -> Dict[str, Any]:
108
+ """Constructs a Slack Block Kit interactive approval prompt for an MRTR escalation."""
109
+ esc_id = escalation["id"]
110
+ agent_id = escalation["agent_id"]
111
+ server = escalation["server_name"]
112
+ tool = escalation["tool_name"]
113
+ principal = escalation.get("principal") or "unknown"
114
+ args_preview = json.dumps(escalation.get("tokenized_arguments") or {}, sort_keys=True)
115
+ violations = escalation.get("violations") or []
116
+ reason = "; ".join(str(v.get("message") or v.get("rule_id") or "") for v in violations) or "Exceeds autonomous bounds"
117
+
118
+ return {
119
+ "text": f"[Piton MRTR] Approval required for {agent_id}: {server}.{tool}",
120
+ "blocks": [
121
+ {
122
+ "type": "header",
123
+ "text": {"type": "plain_text", "text": "Piton MRTR — Human Approval Required"},
124
+ },
125
+ {
126
+ "type": "section",
127
+ "fields": [
128
+ {"type": "mrkdwn", "text": f"*Agent:*\n`{agent_id}`"},
129
+ {"type": "mrkdwn", "text": f"*Tool:*\n`{server}.{tool}`"},
130
+ {"type": "mrkdwn", "text": f"*OBO Principal:*\n`{principal}`"},
131
+ {"type": "mrkdwn", "text": f"*Escalation ID:*\n`{esc_id}`"},
132
+ ],
133
+ },
134
+ {
135
+ "type": "section",
136
+ "text": {"type": "mrkdwn", "text": f"*Reason:* {reason}\n*Tokenized Args:* `{args_preview}`"},
137
+ },
138
+ {
139
+ "type": "actions",
140
+ "elements": [
141
+ {
142
+ "type": "button",
143
+ "text": {"type": "plain_text", "text": "Approve & Sign Token"},
144
+ "style": "primary",
145
+ "action_id": "piton_mrtr_approve",
146
+ "value": esc_id,
147
+ },
148
+ {
149
+ "type": "button",
150
+ "text": {"type": "plain_text", "text": "Deny"},
151
+ "style": "danger",
152
+ "action_id": "piton_mrtr_deny",
153
+ "value": esc_id,
154
+ },
155
+ ],
156
+ },
157
+ ],
158
+ }
159
+
160
+
161
+ class ControlPlaneStore:
162
+ """Thread-safe SQLite backing store for fleet ledgers, drift alerts, and MRTR approvals."""
163
+
164
+ def __init__(self, db_path: str | Path, signing_key: bytes):
165
+ self.db_path = Path(db_path)
166
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
167
+ self.signing_key = signing_key
168
+ self._lock = threading.Lock()
169
+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
170
+ self._conn.row_factory = sqlite3.Row
171
+ self._init_schema()
172
+
173
+ def _init_schema(self) -> None:
174
+ with self._lock, self._conn:
175
+ self._conn.executescript(
176
+ """
177
+ CREATE TABLE IF NOT EXISTS mrtr_approvals (
178
+ id TEXT PRIMARY KEY,
179
+ created_at REAL NOT NULL,
180
+ agent_id TEXT NOT NULL,
181
+ server_name TEXT NOT NULL,
182
+ tool_name TEXT NOT NULL,
183
+ principal TEXT NOT NULL,
184
+ request_state TEXT NOT NULL,
185
+ tokenized_arguments_json TEXT NOT NULL,
186
+ violations_json TEXT NOT NULL,
187
+ status TEXT NOT NULL,
188
+ decided_by TEXT,
189
+ decided_at REAL,
190
+ approval_token TEXT
191
+ );
192
+
193
+ CREATE TABLE IF NOT EXISTS fleet_ledger (
194
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
195
+ timestamp REAL NOT NULL,
196
+ agent_id TEXT NOT NULL,
197
+ traceparent TEXT NOT NULL,
198
+ obo_principal TEXT,
199
+ server_name TEXT NOT NULL,
200
+ tool_name TEXT NOT NULL,
201
+ verdict TEXT NOT NULL,
202
+ latency_ms REAL NOT NULL,
203
+ policy_sha256 TEXT NOT NULL,
204
+ lockfile_sha256 TEXT NOT NULL,
205
+ record_hmac TEXT NOT NULL,
206
+ hmac_verified INTEGER NOT NULL,
207
+ raw_json TEXT NOT NULL
208
+ );
209
+
210
+ CREATE TABLE IF NOT EXISTS drift_events (
211
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
212
+ timestamp REAL NOT NULL,
213
+ agent_id TEXT NOT NULL,
214
+ server_name TEXT NOT NULL,
215
+ tool_name TEXT NOT NULL,
216
+ kind TEXT NOT NULL,
217
+ action TEXT NOT NULL,
218
+ message TEXT NOT NULL
219
+ );
220
+ """
221
+ )
222
+
223
+ def close(self) -> None:
224
+ with self._lock:
225
+ self._conn.close()
226
+
227
+ # ------------------------------------------------------------------
228
+ # MRTR Escalations & Human Approvals
229
+ # ------------------------------------------------------------------
230
+
231
+ def create_escalation(self, payload: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
232
+ request_state = str(payload.get("request_state") or "").strip()
233
+ if not request_state:
234
+ return None, "Missing request_state."
235
+ if verify_and_decode_mrtr_state(request_state, self.signing_key) is None:
236
+ return None, "Rejected escalation: invalid MRTR request_state HMAC signature."
237
+
238
+ esc_id = f"mrtr_{uuid.uuid4().hex[:12]}"
239
+ created_at = float(payload.get("timestamp") or time.time())
240
+ agent_id = str(payload.get("agent_id") or "unknown-agent")
241
+ server_name = str(payload.get("server_name") or "")
242
+ tool_name = str(payload.get("tool_name") or "")
243
+ principal = str(payload.get("principal") or "")
244
+ tok_args = payload.get("tokenized_arguments") or {}
245
+ violations = payload.get("violations") or []
246
+
247
+ with self._lock, self._conn:
248
+ self._conn.execute(
249
+ """
250
+ INSERT INTO mrtr_approvals (
251
+ id, created_at, agent_id, server_name, tool_name, principal,
252
+ request_state, tokenized_arguments_json, violations_json, status
253
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
254
+ """,
255
+ (
256
+ esc_id,
257
+ created_at,
258
+ agent_id,
259
+ server_name,
260
+ tool_name,
261
+ principal,
262
+ request_state,
263
+ json.dumps(tok_args, sort_keys=True),
264
+ json.dumps(violations),
265
+ ),
266
+ )
267
+ return self.get_escalation(esc_id), None
268
+
269
+ def _row_to_escalation(self, row: sqlite3.Row) -> Dict[str, Any]:
270
+ return {
271
+ "id": row["id"],
272
+ "created_at": row["created_at"],
273
+ "agent_id": row["agent_id"],
274
+ "server_name": row["server_name"],
275
+ "tool_name": row["tool_name"],
276
+ "principal": row["principal"],
277
+ "request_state": row["request_state"],
278
+ "tokenized_arguments": json.loads(row["tokenized_arguments_json"]),
279
+ "violations": json.loads(row["violations_json"]),
280
+ "status": row["status"],
281
+ "decided_by": row["decided_by"],
282
+ "decided_at": row["decided_at"],
283
+ "approval_token": row["approval_token"],
284
+ }
285
+
286
+ def get_escalation(self, esc_id: str) -> Optional[Dict[str, Any]]:
287
+ with self._lock:
288
+ row = self._conn.execute("SELECT * FROM mrtr_approvals WHERE id = ?", (esc_id,)).fetchone()
289
+ return self._row_to_escalation(row) if row else None
290
+
291
+ def list_escalations(self, status: Optional[str] = None, limit: int = 100) -> List[Dict[str, Any]]:
292
+ with self._lock:
293
+ if status:
294
+ rows = self._conn.execute(
295
+ "SELECT * FROM mrtr_approvals WHERE status = ? ORDER BY created_at DESC LIMIT ?",
296
+ (status, limit),
297
+ ).fetchall()
298
+ else:
299
+ rows = self._conn.execute(
300
+ "SELECT * FROM mrtr_approvals ORDER BY created_at DESC LIMIT ?",
301
+ (limit,),
302
+ ).fetchall()
303
+ return [self._row_to_escalation(r) for r in rows]
304
+
305
+ def decide_escalation(
306
+ self, esc_id: str, approve: bool, approver: str
307
+ ) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
308
+ if not approver.strip():
309
+ return None, "Approver identity is required."
310
+ esc = self.get_escalation(esc_id)
311
+ if not esc:
312
+ return None, "Escalation not found."
313
+ if esc["status"] != "pending":
314
+ return esc, f"Escalation already decided ({esc['status']})."
315
+
316
+ now = time.time()
317
+ approval_token: Optional[str] = None
318
+ new_status = "denied"
319
+ if approve:
320
+ tok, err = mint_approved_mrtr_token(esc["request_state"], self.signing_key)
321
+ if err or not tok:
322
+ return None, err or "Failed to mint MRTR approval token."
323
+ approval_token = tok
324
+ new_status = "approved"
325
+
326
+ with self._lock, self._conn:
327
+ self._conn.execute(
328
+ """
329
+ UPDATE mrtr_approvals
330
+ SET status = ?, decided_by = ?, decided_at = ?, approval_token = ?
331
+ WHERE id = ?
332
+ """,
333
+ (new_status, approver.strip(), now, approval_token, esc_id),
334
+ )
335
+ return self.get_escalation(esc_id), None
336
+
337
+ # ------------------------------------------------------------------
338
+ # Central Fleet Signed Decision Ledger & Drift Alerts
339
+ # ------------------------------------------------------------------
340
+
341
+ def ingest_ledger_record(self, record: Dict[str, Any]) -> Tuple[bool, bool]:
342
+ """Stores a DecisionLedgerRecord and returns `(stored, hmac_verified)`."""
343
+ verified = verify_decision_record_hmac(record, self.signing_key)
344
+ with self._lock, self._conn:
345
+ self._conn.execute(
346
+ """
347
+ INSERT INTO fleet_ledger (
348
+ timestamp, agent_id, traceparent, obo_principal, server_name, tool_name,
349
+ verdict, latency_ms, policy_sha256, lockfile_sha256, record_hmac, hmac_verified, raw_json
350
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
351
+ """,
352
+ (
353
+ float(record.get("timestamp") or time.time()),
354
+ str(record.get("agent_id") or "unknown"),
355
+ str(record.get("traceparent") or ""),
356
+ record.get("obo_principal"),
357
+ str(record.get("server_name") or ""),
358
+ str(record.get("tool_name") or ""),
359
+ str(record.get("verdict") or ""),
360
+ float(record.get("latency_ms") or 0.0),
361
+ str(record.get("policy_sha256") or ""),
362
+ str(record.get("lockfile_sha256") or ""),
363
+ str(record.get("record_hmac") or ""),
364
+ 1 if verified else 0,
365
+ json.dumps(record, sort_keys=True),
366
+ ),
367
+ )
368
+ return True, verified
369
+
370
+ def ingest_drift_events(self, payload: Dict[str, Any]) -> int:
371
+ ts = float(payload.get("timestamp") or time.time())
372
+ agent_id = str(payload.get("agent_id") or "unknown")
373
+ server_name = str(payload.get("server_name") or "")
374
+ drifts = payload.get("drifts") or []
375
+ inserted = 0
376
+ with self._lock, self._conn:
377
+ for d in drifts:
378
+ if not isinstance(d, dict):
379
+ continue
380
+ self._conn.execute(
381
+ """
382
+ INSERT INTO drift_events (timestamp, agent_id, server_name, tool_name, kind, action, message)
383
+ VALUES (?, ?, ?, ?, ?, ?, ?)
384
+ """,
385
+ (
386
+ ts,
387
+ agent_id,
388
+ str(d.get("server_name") or server_name),
389
+ str(d.get("tool_name") or ""),
390
+ str(d.get("kind") or "drift"),
391
+ str(d.get("action") or "warn"),
392
+ str(d.get("message") or ""),
393
+ ),
394
+ )
395
+ inserted += 1
396
+ return inserted
397
+
398
+ def list_recent_ledger(self, limit: int = 50, agent_id: Optional[str] = None) -> List[Dict[str, Any]]:
399
+ with self._lock:
400
+ if agent_id:
401
+ rows = self._conn.execute(
402
+ "SELECT hmac_verified, raw_json FROM fleet_ledger WHERE agent_id = ? ORDER BY id DESC LIMIT ?",
403
+ (agent_id, limit),
404
+ ).fetchall()
405
+ else:
406
+ rows = self._conn.execute(
407
+ "SELECT hmac_verified, raw_json FROM fleet_ledger ORDER BY id DESC LIMIT ?",
408
+ (limit,),
409
+ ).fetchall()
410
+ out = []
411
+ for r in rows:
412
+ item = json.loads(r["raw_json"])
413
+ item["hmac_verified"] = bool(r["hmac_verified"])
414
+ out.append(item)
415
+ return out
416
+
417
+ def list_drift_events(self, limit: int = 50) -> List[Dict[str, Any]]:
418
+ with self._lock:
419
+ rows = self._conn.execute(
420
+ "SELECT * FROM drift_events ORDER BY id DESC LIMIT ?", (limit,)
421
+ ).fetchall()
422
+ return [dict(r) for r in rows]
423
+
424
+ def get_fleet_readiness(self) -> Dict[str, Any]:
425
+ """Computes per-agent `shadow -> enforce` readiness scorecards across the fleet."""
426
+ with self._lock:
427
+ ledger_rows = self._conn.execute(
428
+ """
429
+ SELECT
430
+ agent_id,
431
+ COUNT(*) AS total_calls,
432
+ SUM(CASE WHEN verdict = 'allow' THEN 1 ELSE 0 END) AS allowed_calls,
433
+ SUM(CASE WHEN verdict = 'shadow_deny' THEN 1 ELSE 0 END) AS shadow_denied_calls,
434
+ SUM(CASE WHEN verdict = 'deny' THEN 1 ELSE 0 END) AS denied_calls,
435
+ SUM(CASE WHEN verdict = 'mrtr_escalate' THEN 1 ELSE 0 END) AS mrtr_escalated_calls,
436
+ SUM(hmac_verified) AS verified_hmac_records,
437
+ AVG(latency_ms) AS avg_latency_ms
438
+ FROM fleet_ledger
439
+ GROUP BY agent_id
440
+ ORDER BY total_calls DESC
441
+ """
442
+ ).fetchall()
443
+ drift_rows = self._conn.execute(
444
+ "SELECT agent_id, COUNT(*) AS drift_count FROM drift_events GROUP BY agent_id"
445
+ ).fetchall()
446
+ pending_mrtr = self._conn.execute(
447
+ "SELECT COUNT(*) AS cnt FROM mrtr_approvals WHERE status = 'pending'"
448
+ ).fetchone()["cnt"]
449
+
450
+ drift_by_agent = {r["agent_id"]: int(r["drift_count"]) for r in drift_rows}
451
+ agents = []
452
+ for r in ledger_rows:
453
+ aid = r["agent_id"]
454
+ total = int(r["total_calls"])
455
+ shadow_denies = int(r["shadow_denied_calls"] or 0)
456
+ drifts = drift_by_agent.get(aid, 0)
457
+ shadow_block_rate = round((shadow_denies / total) * 100.0, 2) if total > 0 else 0.0
458
+ agents.append(
459
+ {
460
+ "agent_id": aid,
461
+ "total_calls": total,
462
+ "allowed_calls": int(r["allowed_calls"] or 0),
463
+ "shadow_denied_calls": shadow_denies,
464
+ "denied_calls": int(r["denied_calls"] or 0),
465
+ "mrtr_escalated_calls": int(r["mrtr_escalated_calls"] or 0),
466
+ "verified_hmac_records": int(r["verified_hmac_records"] or 0),
467
+ "avg_latency_ms": round(float(r["avg_latency_ms"] or 0.0), 2),
468
+ "drift_alerts": drifts,
469
+ "shadow_block_rate_pct": shadow_block_rate,
470
+ "ready_to_enforce": total > 0 and shadow_denies == 0 and drifts == 0,
471
+ }
472
+ )
473
+ return {
474
+ "generated_at": time.time(),
475
+ "pending_mrtr_approvals": int(pending_mrtr),
476
+ "agents": agents,
477
+ }
478
+
479
+ def build_signed_audit_bundle(self, agent_id: Optional[str] = None) -> Dict[str, Any]:
480
+ """Generates a tamper-evident SOC2 / EU AI Act signed compliance export bundle."""
481
+ bundle_body = {
482
+ "schema": "piton.compliance.audit_bundle.v1",
483
+ "exported_at": time.time(),
484
+ "agent_filter": agent_id or "*",
485
+ "fleet_readiness": self.get_fleet_readiness(),
486
+ "mrtr_approvals": self.list_escalations(limit=500),
487
+ "drift_events": self.list_drift_events(limit=500),
488
+ "decision_ledger": self.list_recent_ledger(limit=1000, agent_id=agent_id),
489
+ }
490
+ canonical = json.dumps(bundle_body, sort_keys=True, separators=(",", ":")).encode("utf-8")
491
+ bundle_sha256 = hashlib.sha256(canonical).hexdigest()
492
+ bundle_hmac = _hmac_hex(self.signing_key, canonical)
493
+ return {
494
+ **bundle_body,
495
+ "integrity": {
496
+ "algorithm": "HMAC-SHA256",
497
+ "bundle_sha256": bundle_sha256,
498
+ "bundle_hmac": bundle_hmac,
499
+ },
500
+ }
piton/iac/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """
2
+ Piton Agent Control Loop — Declarative Agent IaC, Day-1 MCP Poisoning Linter,
3
+ Split-Hash MCP Manifest Pinning (piton.lock), and Shadow-to-Enforce Policy Replay.
4
+ """
5
+
6
+ from piton.iac.schema import (
7
+ AgentIaCConfig,
8
+ BoundExceededAction,
9
+ EnforcementMode,
10
+ IdentityConfig,
11
+ LocalDevCredentialSlot,
12
+ ManifestLockfile,
13
+ MCPServerPolicy,
14
+ ParameterBound,
15
+ PinnedServerManifest,
16
+ PinnedToolEntry,
17
+ ToolPolicy,
18
+ ToolTier,
19
+ TrustTier,
20
+ )
21
+
22
+ __all__ = [
23
+ "AgentIaCConfig",
24
+ "BoundExceededAction",
25
+ "EnforcementMode",
26
+ "IdentityConfig",
27
+ "LocalDevCredentialSlot",
28
+ "ManifestLockfile",
29
+ "MCPServerPolicy",
30
+ "ParameterBound",
31
+ "PinnedServerManifest",
32
+ "PinnedToolEntry",
33
+ "ToolPolicy",
34
+ "ToolTier",
35
+ "TrustTier",
36
+ ]