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.
- piton/__init__.py +5 -0
- piton/cli.py +716 -0
- piton/control_plane/__init__.py +11 -0
- piton/control_plane/server.py +402 -0
- piton/control_plane/store.py +500 -0
- piton/iac/__init__.py +36 -0
- piton/iac/agent_config_lint.py +436 -0
- piton/iac/lockfile.py +420 -0
- piton/iac/mcp_probe.py +582 -0
- piton/iac/poisoning_lint.py +197 -0
- piton/iac/replay.py +896 -0
- piton/iac/scanner.py +350 -0
- piton/iac/schema.py +256 -0
- piton_cli-0.4.2.dist-info/METADATA +192 -0
- piton_cli-0.4.2.dist-info/RECORD +19 -0
- piton_cli-0.4.2.dist-info/WHEEL +5 -0
- piton_cli-0.4.2.dist-info/entry_points.txt +3 -0
- piton_cli-0.4.2.dist-info/licenses/LICENSE +21 -0
- piton_cli-0.4.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Piton Control Plane:
|
|
3
|
+
- Live MCP 2026-07-28 MRTR Human-in-the-Loop Approval Bridge (REST + Slack Block Kit + Web UI)
|
|
4
|
+
- Central Fleet Signed Decision Ledger Collector (Go<->Python HMAC verification)
|
|
5
|
+
- Fleet-wide `shadow -> enforce` Readiness Scorecards & Drift Alerts
|
|
6
|
+
- Tamper-Evident SOC2 / EU AI Act Signed Audit Bundle Exporter
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from piton.control_plane.store import ControlPlaneStore, verify_slack_signature
|
|
10
|
+
|
|
11
|
+
__all__ = ["ControlPlaneStore", "verify_slack_signature"]
|
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Piton Control Plane HTTP Server & Embedded Governance UI.
|
|
3
|
+
|
|
4
|
+
Pure Python stdlib (`http.server` + `sqlite3`) — zero heavy runtime dependencies:
|
|
5
|
+
- Live MRTR Approval Bridge (REST + Slack Block Kit webhook + verified Slack interactions)
|
|
6
|
+
- Multi-Pod Signed Decision Ledger Collector (`POST /api/v1/ledger/ingest`)
|
|
7
|
+
- Live MCP Lockfile Drift Collector (`POST /api/v1/drift/ingest`)
|
|
8
|
+
- Fleet `shadow -> enforce` Readiness Scorecards (`GET /api/v1/fleet/readiness`)
|
|
9
|
+
- Tamper-Evident Signed SOC2 / EU AI Act Audit Bundle Export (`GET /api/v1/audit/export`)
|
|
10
|
+
- Embedded Live Web UI (`GET /`) for 1-click MRTR approvals and fleet readiness
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import threading
|
|
16
|
+
import urllib.parse
|
|
17
|
+
import urllib.request
|
|
18
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Dict, Optional
|
|
21
|
+
|
|
22
|
+
from piton.control_plane.store import (
|
|
23
|
+
ControlPlaneStore,
|
|
24
|
+
build_slack_mrtr_blocks,
|
|
25
|
+
verify_slack_signature,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
MAX_REQUEST_BYTES = 2 * 1024 * 1024 # 2 MiB
|
|
29
|
+
|
|
30
|
+
DASHBOARD_HTML = """<!doctype html>
|
|
31
|
+
<html lang="en">
|
|
32
|
+
<head>
|
|
33
|
+
<meta charset="utf-8" />
|
|
34
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
35
|
+
<title>Piton Control Plane — Fleet Governance & MRTR Approvals</title>
|
|
36
|
+
<style>
|
|
37
|
+
:root {
|
|
38
|
+
--bg: #0b0f17; --card: #121826; --border: #232d42;
|
|
39
|
+
--text: #e6edf7; --muted: #8b9bb4; --accent: #f97316;
|
|
40
|
+
--ok: #22c55e; --warn: #eab308; --bad: #ef4444;
|
|
41
|
+
}
|
|
42
|
+
* { box-sizing: border-box; }
|
|
43
|
+
body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); }
|
|
44
|
+
header { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; border-bottom: 1px solid var(--border); background: #0e1421; }
|
|
45
|
+
h1 { font-size: 18px; margin: 0; letter-spacing: 0.2px; }
|
|
46
|
+
h1 span { color: var(--accent); }
|
|
47
|
+
.actions { display: flex; gap: 10px; align-items: center; }
|
|
48
|
+
input, button { font: inherit; border-radius: 6px; border: 1px solid var(--border); padding: 7px 12px; }
|
|
49
|
+
input { background: #0b0f17; color: var(--text); width: 220px; }
|
|
50
|
+
button { background: var(--accent); color: #0b0f17; font-weight: 600; cursor: pointer; border: none; }
|
|
51
|
+
button.secondary { background: #1e293b; color: var(--text); border: 1px solid var(--border); }
|
|
52
|
+
button.approve { background: var(--ok); color: #062812; }
|
|
53
|
+
button.deny { background: var(--bad); color: #fff; }
|
|
54
|
+
main { max-width: 1280px; margin: 20px auto; padding: 0 20px; display: grid; gap: 20px; }
|
|
55
|
+
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px 20px; }
|
|
56
|
+
.card h2 { margin: 0 0 12px; font-size: 15px; color: #cbd5e1; display: flex; justify-content: space-between; }
|
|
57
|
+
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
58
|
+
th, td { text-align: left; padding: 9px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
|
59
|
+
th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; }
|
|
60
|
+
.pill { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
|
|
61
|
+
.pill.ok { background: rgba(34,197,94,0.18); color: var(--ok); }
|
|
62
|
+
.pill.warn { background: rgba(234,179,8,0.18); color: var(--warn); }
|
|
63
|
+
.pill.bad { background: rgba(239,68,68,0.18); color: var(--bad); }
|
|
64
|
+
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: #93c5fd; word-break: break-all; }
|
|
65
|
+
.muted { color: var(--muted); }
|
|
66
|
+
.btn-row { display: flex; gap: 6px; }
|
|
67
|
+
</style>
|
|
68
|
+
</head>
|
|
69
|
+
<body>
|
|
70
|
+
<header>
|
|
71
|
+
<h1><span>PITON</span> Enterprise Control Plane</h1>
|
|
72
|
+
<div class="actions">
|
|
73
|
+
<input id="approver" value="secops@acme.com" placeholder="Approver email" />
|
|
74
|
+
<button class="secondary" onclick="refreshAll()">Refresh</button>
|
|
75
|
+
<button onclick="exportAudit()">Export Signed SOC2 Audit</button>
|
|
76
|
+
</div>
|
|
77
|
+
</header>
|
|
78
|
+
<main>
|
|
79
|
+
<section class="card">
|
|
80
|
+
<h2>Pending & Recent MRTR Human Approvals <span id="pendingCount" class="pill warn">0 pending</span></h2>
|
|
81
|
+
<table>
|
|
82
|
+
<thead><tr><th>ID</th><th>Agent / Tool</th><th>OBO Principal</th><th>Tokenized Args & Violation</th><th>Status</th><th>Action / Token</th></tr></thead>
|
|
83
|
+
<tbody id="mrtrBody"><tr><td colspan="6" class="muted">Loading...</td></tr></tbody>
|
|
84
|
+
</table>
|
|
85
|
+
</section>
|
|
86
|
+
|
|
87
|
+
<section class="card">
|
|
88
|
+
<h2>Fleet Shadow → Enforce Readiness Scorecards</h2>
|
|
89
|
+
<table>
|
|
90
|
+
<thead><tr><th>Agent</th><th>Total Calls</th><th>Allowed</th><th>Shadow Denies</th><th>MRTR</th><th>Drift Alerts</th><th>HMAC Verified</th><th>Avg Latency</th><th>Ready?</th></tr></thead>
|
|
91
|
+
<tbody id="fleetBody"><tr><td colspan="9" class="muted">Loading...</td></tr></tbody>
|
|
92
|
+
</table>
|
|
93
|
+
</section>
|
|
94
|
+
|
|
95
|
+
<section class="card">
|
|
96
|
+
<h2>MCP Lockfile Drift & Poisoning Alerts</h2>
|
|
97
|
+
<table>
|
|
98
|
+
<thead><tr><th>Agent</th><th>Server.Tool</th><th>Kind</th><th>Action</th><th>Message</th></tr></thead>
|
|
99
|
+
<tbody id="driftBody"><tr><td colspan="5" class="muted">Loading...</td></tr></tbody>
|
|
100
|
+
</table>
|
|
101
|
+
</section>
|
|
102
|
+
|
|
103
|
+
<section class="card">
|
|
104
|
+
<h2>Recent Signed Decision Ledger</h2>
|
|
105
|
+
<table>
|
|
106
|
+
<thead><tr><th>Agent</th><th>Server.Tool</th><th>OBO Principal</th><th>Verdict</th><th>HMAC</th><th>Latency</th></tr></thead>
|
|
107
|
+
<tbody id="ledgerBody"><tr><td colspan="6" class="muted">Loading...</td></tr></tbody>
|
|
108
|
+
</table>
|
|
109
|
+
</section>
|
|
110
|
+
</main>
|
|
111
|
+
<script>
|
|
112
|
+
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
|
113
|
+
async function decide(id, action) {
|
|
114
|
+
const approver = document.getElementById('approver').value || 'secops@acme.com';
|
|
115
|
+
await fetch(`/api/v1/mrtr/approvals/${encodeURIComponent(id)}/${action}`, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: { 'Content-Type': 'application/json', 'X-Approver-Email': approver },
|
|
118
|
+
body: JSON.stringify({ approver })
|
|
119
|
+
});
|
|
120
|
+
await refreshAll();
|
|
121
|
+
}
|
|
122
|
+
async function exportAudit() {
|
|
123
|
+
const res = await fetch('/api/v1/audit/export');
|
|
124
|
+
const data = await res.json();
|
|
125
|
+
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
|
126
|
+
const a = document.createElement('a');
|
|
127
|
+
a.href = URL.createObjectURL(blob);
|
|
128
|
+
a.download = `piton-signed-audit-${Date.now()}.json`;
|
|
129
|
+
a.click();
|
|
130
|
+
}
|
|
131
|
+
async function refreshAll() {
|
|
132
|
+
const [mrtr, fleet, drifts, ledger] = await Promise.all([
|
|
133
|
+
fetch('/api/v1/mrtr/approvals').then(r => r.json()),
|
|
134
|
+
fetch('/api/v1/fleet/readiness').then(r => r.json()),
|
|
135
|
+
fetch('/api/v1/drift/events').then(r => r.json()),
|
|
136
|
+
fetch('/api/v1/ledger/recent').then(r => r.json()),
|
|
137
|
+
]);
|
|
138
|
+
const pending = (mrtr.approvals || []).filter(a => a.status === 'pending').length;
|
|
139
|
+
document.getElementById('pendingCount').textContent = `${pending} pending`;
|
|
140
|
+
document.getElementById('mrtrBody').innerHTML = (mrtr.approvals || []).length ? mrtr.approvals.map(a => `
|
|
141
|
+
<tr>
|
|
142
|
+
<td><code>${esc(a.id)}</code></td>
|
|
143
|
+
<td><b>${esc(a.agent_id)}</b><br/><code>${esc(a.server_name)}.${esc(a.tool_name)}</code></td>
|
|
144
|
+
<td><code>${esc(a.principal)}</code></td>
|
|
145
|
+
<td><code>${esc(JSON.stringify(a.tokenized_arguments))}</code><br/><span class="muted">${esc((a.violations||[]).map(v=>v.message||v.rule_id).join('; '))}</span></td>
|
|
146
|
+
<td><span class="pill ${a.status==='approved'?'ok':a.status==='denied'?'bad':'warn'}">${esc(a.status)}</span>${a.decided_by?`<br/><span class="muted">${esc(a.decided_by)}</span>`:''}</td>
|
|
147
|
+
<td>${a.status==='pending'
|
|
148
|
+
? `<div class="btn-row"><button class="approve" onclick="decide('${esc(a.id)}','approve')">Approve</button><button class="deny" onclick="decide('${esc(a.id)}','deny')">Deny</button></div>`
|
|
149
|
+
: (a.approval_token ? `<code>${esc(a.approval_token.slice(0, 36))}...</code>` : '<span class="muted">—</span>')}</td>
|
|
150
|
+
</tr>`).join('') : '<tr><td colspan="6" class="muted">No MRTR escalations recorded yet.</td></tr>';
|
|
151
|
+
|
|
152
|
+
document.getElementById('fleetBody').innerHTML = (fleet.agents || []).length ? fleet.agents.map(ag => `
|
|
153
|
+
<tr>
|
|
154
|
+
<td><b>${esc(ag.agent_id)}</b></td>
|
|
155
|
+
<td>${ag.total_calls}</td>
|
|
156
|
+
<td>${ag.allowed_calls}</td>
|
|
157
|
+
<td>${ag.shadow_denied_calls} (${ag.shadow_block_rate_pct}%)</td>
|
|
158
|
+
<td>${ag.mrtr_escalated_calls}</td>
|
|
159
|
+
<td>${ag.drift_alerts}</td>
|
|
160
|
+
<td>${ag.verified_hmac_records}/${ag.total_calls}</td>
|
|
161
|
+
<td>${ag.avg_latency_ms}ms</td>
|
|
162
|
+
<td><span class="pill ${ag.ready_to_enforce?'ok':'warn'}">${ag.ready_to_enforce?'READY':'CALIBRATE'}</span></td>
|
|
163
|
+
</tr>`).join('') : '<tr><td colspan="9" class="muted">No agent telemetry ingested yet.</td></tr>';
|
|
164
|
+
|
|
165
|
+
document.getElementById('driftBody').innerHTML = (drifts.events || []).length ? drifts.events.map(d => `
|
|
166
|
+
<tr>
|
|
167
|
+
<td><b>${esc(d.agent_id)}</b></td>
|
|
168
|
+
<td><code>${esc(d.server_name)}.${esc(d.tool_name)}</code></td>
|
|
169
|
+
<td><code>${esc(d.kind)}</code></td>
|
|
170
|
+
<td><span class="pill ${d.action==='block'?'bad':'warn'}">${esc(d.action)}</span></td>
|
|
171
|
+
<td>${esc(d.message)}</td>
|
|
172
|
+
</tr>`).join('') : '<tr><td colspan="5" class="muted">No lockfile drift alerts.</td></tr>';
|
|
173
|
+
|
|
174
|
+
document.getElementById('ledgerBody').innerHTML = (ledger.records || []).length ? ledger.records.map(r => `
|
|
175
|
+
<tr>
|
|
176
|
+
<td><b>${esc(r.agent_id)}</b></td>
|
|
177
|
+
<td><code>${esc(r.server_name)}.${esc(r.tool_name)}</code></td>
|
|
178
|
+
<td><code>${esc(r.obo_principal || '-')}</code></td>
|
|
179
|
+
<td><span class="pill ${r.verdict==='allow'?'ok':r.verdict==='deny'?'bad':'warn'}">${esc(r.verdict)}</span></td>
|
|
180
|
+
<td><span class="pill ${r.hmac_verified?'ok':'bad'}">${r.hmac_verified?'VERIFIED':'INVALID'}</span></td>
|
|
181
|
+
<td>${Number(r.latency_ms||0).toFixed(1)}ms</td>
|
|
182
|
+
</tr>`).join('') : '<tr><td colspan="6" class="muted">No ledger records ingested yet.</td></tr>';
|
|
183
|
+
}
|
|
184
|
+
refreshAll();
|
|
185
|
+
setInterval(refreshAll, 5000);
|
|
186
|
+
</script>
|
|
187
|
+
</body>
|
|
188
|
+
</html>
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _post_slack_webhook_async(webhook_url: str, payload: Dict[str, Any]) -> None:
|
|
193
|
+
def _send() -> None:
|
|
194
|
+
try:
|
|
195
|
+
req = urllib.request.Request(
|
|
196
|
+
webhook_url,
|
|
197
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
198
|
+
method="POST",
|
|
199
|
+
headers={"Content-Type": "application/json"},
|
|
200
|
+
)
|
|
201
|
+
with urllib.request.urlopen(req, timeout=4) as resp:
|
|
202
|
+
resp.read(4096)
|
|
203
|
+
except Exception:
|
|
204
|
+
pass
|
|
205
|
+
|
|
206
|
+
threading.Thread(target=_send, daemon=True).start()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def create_control_plane_server(
|
|
210
|
+
host: str,
|
|
211
|
+
port: int,
|
|
212
|
+
db_path: str | Path,
|
|
213
|
+
signing_key: bytes,
|
|
214
|
+
api_key: str = "",
|
|
215
|
+
slack_webhook_url: str = "",
|
|
216
|
+
slack_signing_secret: str = "",
|
|
217
|
+
) -> tuple[ThreadingHTTPServer, ControlPlaneStore]:
|
|
218
|
+
"""Creates a threaded Control Plane HTTP server backed by SQLite."""
|
|
219
|
+
store = ControlPlaneStore(db_path=db_path, signing_key=signing_key)
|
|
220
|
+
api_key_clean = api_key.strip()
|
|
221
|
+
slack_url_clean = slack_webhook_url.strip()
|
|
222
|
+
slack_secret_clean = slack_signing_secret.strip()
|
|
223
|
+
|
|
224
|
+
class ControlPlaneHandler(BaseHTTPRequestHandler):
|
|
225
|
+
def log_message(self, fmt: str, *args: Any) -> None:
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
def _send_json(self, code: int, obj: Any) -> None:
|
|
229
|
+
body = json.dumps(obj, sort_keys=True).encode("utf-8")
|
|
230
|
+
self.send_response(code)
|
|
231
|
+
self.send_header("Content-Type", "application/json")
|
|
232
|
+
self.send_header("Content-Length", str(len(body)))
|
|
233
|
+
self.end_headers()
|
|
234
|
+
self.wfile.write(body)
|
|
235
|
+
|
|
236
|
+
def _send_html(self, code: int, html: str) -> None:
|
|
237
|
+
body = html.encode("utf-8")
|
|
238
|
+
self.send_response(code)
|
|
239
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
240
|
+
self.send_header("Content-Length", str(len(body)))
|
|
241
|
+
self.end_headers()
|
|
242
|
+
self.wfile.write(body)
|
|
243
|
+
|
|
244
|
+
def _read_body(self) -> Optional[bytes]:
|
|
245
|
+
try:
|
|
246
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
247
|
+
except ValueError:
|
|
248
|
+
return None
|
|
249
|
+
if length < 0 or length > MAX_REQUEST_BYTES:
|
|
250
|
+
return None
|
|
251
|
+
return self.rfile.read(length) if length > 0 else b""
|
|
252
|
+
|
|
253
|
+
def _check_api_key(self) -> bool:
|
|
254
|
+
if not api_key_clean:
|
|
255
|
+
return True
|
|
256
|
+
provided = (self.headers.get("X-Piton-Control-Key") or "").strip()
|
|
257
|
+
return hmac.compare_digest(provided, api_key_clean)
|
|
258
|
+
|
|
259
|
+
def do_GET(self) -> None:
|
|
260
|
+
parsed = urllib.parse.urlparse(self.path)
|
|
261
|
+
path = parsed.path.rstrip("/") or "/"
|
|
262
|
+
qs = urllib.parse.parse_qs(parsed.query)
|
|
263
|
+
|
|
264
|
+
if path == "/":
|
|
265
|
+
self._send_html(200, DASHBOARD_HTML)
|
|
266
|
+
return
|
|
267
|
+
if path == "/healthz":
|
|
268
|
+
self._send_json(200, {"status": "ok", "service": "piton-control-plane"})
|
|
269
|
+
return
|
|
270
|
+
if not self._check_api_key():
|
|
271
|
+
self._send_json(401, {"error": "unauthorized"})
|
|
272
|
+
return
|
|
273
|
+
|
|
274
|
+
if path == "/api/v1/mrtr/approvals":
|
|
275
|
+
status = (qs.get("status") or [None])[0]
|
|
276
|
+
self._send_json(200, {"approvals": store.list_escalations(status=status)})
|
|
277
|
+
return
|
|
278
|
+
if path.startswith("/api/v1/mrtr/approvals/"):
|
|
279
|
+
esc_id = path[len("/api/v1/mrtr/approvals/") :]
|
|
280
|
+
esc = store.get_escalation(esc_id)
|
|
281
|
+
if not esc:
|
|
282
|
+
self._send_json(404, {"error": "not_found"})
|
|
283
|
+
return
|
|
284
|
+
self._send_json(200, esc)
|
|
285
|
+
return
|
|
286
|
+
if path == "/api/v1/fleet/readiness":
|
|
287
|
+
self._send_json(200, store.get_fleet_readiness())
|
|
288
|
+
return
|
|
289
|
+
if path == "/api/v1/ledger/recent":
|
|
290
|
+
agent_id = (qs.get("agent_id") or [None])[0]
|
|
291
|
+
self._send_json(200, {"records": store.list_recent_ledger(agent_id=agent_id)})
|
|
292
|
+
return
|
|
293
|
+
if path == "/api/v1/drift/events":
|
|
294
|
+
self._send_json(200, {"events": store.list_drift_events()})
|
|
295
|
+
return
|
|
296
|
+
if path == "/api/v1/audit/export":
|
|
297
|
+
agent_id = (qs.get("agent_id") or [None])[0]
|
|
298
|
+
self._send_json(200, store.build_signed_audit_bundle(agent_id=agent_id))
|
|
299
|
+
return
|
|
300
|
+
|
|
301
|
+
self._send_json(404, {"error": "not_found"})
|
|
302
|
+
|
|
303
|
+
def do_POST(self) -> None:
|
|
304
|
+
parsed = urllib.parse.urlparse(self.path)
|
|
305
|
+
path = parsed.path.rstrip("/") or "/"
|
|
306
|
+
raw = self._read_body()
|
|
307
|
+
if raw is None:
|
|
308
|
+
self._send_json(413, {"error": "payload_too_large"})
|
|
309
|
+
return
|
|
310
|
+
|
|
311
|
+
# Slack interactive callback uses Slack HMAC signature verification
|
|
312
|
+
if path == "/api/v1/slack/interactions":
|
|
313
|
+
ts = self.headers.get("X-Slack-Request-Timestamp", "")
|
|
314
|
+
sig = self.headers.get("X-Slack-Signature", "")
|
|
315
|
+
if not verify_slack_signature(slack_secret_clean, ts, raw, sig):
|
|
316
|
+
self._send_json(401, {"error": "invalid_slack_signature"})
|
|
317
|
+
return
|
|
318
|
+
form = urllib.parse.parse_qs(raw.decode("utf-8", errors="replace"))
|
|
319
|
+
payload_raw = (form.get("payload") or ["{}"])[0]
|
|
320
|
+
try:
|
|
321
|
+
interaction = json.loads(payload_raw)
|
|
322
|
+
except Exception:
|
|
323
|
+
self._send_json(400, {"error": "invalid_slack_payload"})
|
|
324
|
+
return
|
|
325
|
+
actions = interaction.get("actions") or []
|
|
326
|
+
if not actions:
|
|
327
|
+
self._send_json(400, {"error": "missing_actions"})
|
|
328
|
+
return
|
|
329
|
+
action = actions[0]
|
|
330
|
+
esc_id = str(action.get("value") or "")
|
|
331
|
+
approve = action.get("action_id") == "piton_mrtr_approve"
|
|
332
|
+
user = interaction.get("user") or {}
|
|
333
|
+
approver = str(user.get("username") or user.get("name") or user.get("id") or "slack-user")
|
|
334
|
+
esc, err = store.decide_escalation(esc_id, approve=approve, approver=f"slack:{approver}")
|
|
335
|
+
if err:
|
|
336
|
+
self._send_json(400, {"error": err})
|
|
337
|
+
return
|
|
338
|
+
self._send_json(
|
|
339
|
+
200,
|
|
340
|
+
{
|
|
341
|
+
"text": f"Escalation `{esc_id}` *{esc['status'].upper()}* by `{esc['decided_by']}`.",
|
|
342
|
+
"escalation": esc,
|
|
343
|
+
},
|
|
344
|
+
)
|
|
345
|
+
return
|
|
346
|
+
|
|
347
|
+
if not self._check_api_key():
|
|
348
|
+
self._send_json(401, {"error": "unauthorized"})
|
|
349
|
+
return
|
|
350
|
+
|
|
351
|
+
try:
|
|
352
|
+
body = json.loads(raw.decode("utf-8") or "{}")
|
|
353
|
+
except Exception:
|
|
354
|
+
self._send_json(400, {"error": "invalid_json"})
|
|
355
|
+
return
|
|
356
|
+
if not isinstance(body, dict):
|
|
357
|
+
self._send_json(400, {"error": "expected_json_object"})
|
|
358
|
+
return
|
|
359
|
+
|
|
360
|
+
if path == "/api/v1/mrtr/escalations":
|
|
361
|
+
esc, err = store.create_escalation(body)
|
|
362
|
+
if err or not esc:
|
|
363
|
+
self._send_json(400, {"error": err or "invalid_escalation"})
|
|
364
|
+
return
|
|
365
|
+
if slack_url_clean:
|
|
366
|
+
_post_slack_webhook_async(slack_url_clean, build_slack_mrtr_blocks(esc))
|
|
367
|
+
self._send_json(201, esc)
|
|
368
|
+
return
|
|
369
|
+
|
|
370
|
+
if path.startswith("/api/v1/mrtr/approvals/") and (
|
|
371
|
+
path.endswith("/approve") or path.endswith("/deny")
|
|
372
|
+
):
|
|
373
|
+
approve = path.endswith("/approve")
|
|
374
|
+
suffix_len = len("/approve") if approve else len("/deny")
|
|
375
|
+
esc_id = path[len("/api/v1/mrtr/approvals/") : -suffix_len]
|
|
376
|
+
approver = str(
|
|
377
|
+
self.headers.get("X-Approver-Email")
|
|
378
|
+
or body.get("approver")
|
|
379
|
+
or ""
|
|
380
|
+
).strip()
|
|
381
|
+
esc, err = store.decide_escalation(esc_id, approve=approve, approver=approver)
|
|
382
|
+
if err or not esc:
|
|
383
|
+
code = 404 if err == "Escalation not found." else 400
|
|
384
|
+
self._send_json(code, {"error": err or "decision_failed"})
|
|
385
|
+
return
|
|
386
|
+
self._send_json(200, esc)
|
|
387
|
+
return
|
|
388
|
+
|
|
389
|
+
if path == "/api/v1/ledger/ingest":
|
|
390
|
+
stored, verified = store.ingest_ledger_record(body)
|
|
391
|
+
self._send_json(201, {"stored": stored, "hmac_verified": verified})
|
|
392
|
+
return
|
|
393
|
+
|
|
394
|
+
if path == "/api/v1/drift/ingest":
|
|
395
|
+
count = store.ingest_drift_events(body)
|
|
396
|
+
self._send_json(201, {"ingested": count})
|
|
397
|
+
return
|
|
398
|
+
|
|
399
|
+
self._send_json(404, {"error": "not_found"})
|
|
400
|
+
|
|
401
|
+
httpd = ThreadingHTTPServer((host, port), ControlPlaneHandler)
|
|
402
|
+
return httpd, store
|