warmplane 0.29.0

Local control plane that keeps MCP sessions warm with compact capability/resource/prompt facades.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Rust guideline compliant 2026-08-26

//! Multi-platform ChatOps payload formatting and incoming callback resolution.
//!
//! Formats outbound notification events into platform-specific rich cards:
//! - Generic JSON
//! - Slack Block Kit (`format: "slack"`) with interactive action buttons
//! - Discord Embeds (`format: "discord"`) with component buttons
//! - Microsoft Teams Adaptive Cards (`format: "teams"`)
//!
//! Also provides signature verification for incoming webhook callbacks.

use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

/// Payload layout format for outbound webhooks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WebhookFormat {
    /// Standard structured Warmplane JSON payload.
    #[default]
    Generic,
    /// Slack Block Kit payload with interactive blocks.
    Slack,
    /// Discord Embed with action buttons.
    Discord,
    /// Microsoft Teams Adaptive Card format.
    Teams,
}

/// Formats an outbound webhook payload based on the configured format.
pub fn format_webhook_payload(
    format: WebhookFormat,
    event_type: &str,
    data: &Value,
    callback_url: Option<&str>,
) -> Value {
    match format {
        WebhookFormat::Generic => json!({
            "event": event_type,
            "timestamp": std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
            "data": data,
            "callback_url": callback_url,
        }),
        WebhookFormat::Slack => build_slack_payload(event_type, data, callback_url),
        WebhookFormat::Discord => build_discord_payload(event_type, data, callback_url),
        WebhookFormat::Teams => build_teams_payload(event_type, data, callback_url),
    }
}

fn build_slack_payload(event_type: &str, data: &Value, callback_url: Option<&str>) -> Value {
    let title = match event_type {
        "approval.requested" => "🚨 Warmplane: Human Approval Required",
        "circuit_breaker.tripped" => "⚠️ Warmplane: Circuit Breaker Tripped",
        "policy.violation" => "🛡️ Warmplane: Security Policy Violation",
        "task.timeout" => "⏱️ Warmplane: Task Timeout",
        _ => "📢 Warmplane Notification",
    };

    let mut blocks = vec![json!({
        "type": "header",
        "text": {
            "type": "plain_text",
            "text": title,
            "emoji": true
        }
    })];

    if event_type == "approval.requested" {
        let ticket_id = data.get("id").and_then(Value::as_str).unwrap_or("unknown");
        let cap_id = data
            .get("capability_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let server_id = data
            .get("server_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let args_str = data
            .get("sanitized_args")
            .or_else(|| data.get("args"))
            .map(|a| serde_json::to_string_pretty(a).unwrap_or_else(|_| "{}".to_string()))
            .unwrap_or_else(|| "{}".to_string());

        blocks.push(json!({
            "type": "section",
            "fields": [
                {
                    "type": "mrkdwn",
                    "text": format!("*Capability:*\n`{}`", cap_id)
                },
                {
                    "type": "mrkdwn",
                    "text": format!("*Server:*\n`{}`", server_id)
                },
                {
                    "type": "mrkdwn",
                    "text": format!("*Ticket ID:*\n`{}`", ticket_id)
                },
                {
                    "type": "mrkdwn",
                    "text": "*Expires In:*\n300 seconds"
                }
            ]
        }));

        blocks.push(json!({
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": format!("*Parameters:*\n```{}```", args_str)
            }
        }));

        if let Some(cb_url) = callback_url {
            blocks.push(json!({
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "✅ Approve",
                            "emoji": true
                        },
                        "style": "primary",
                        "value": json!({
                            "action": "approve",
                            "ticket_id": ticket_id,
                            "callback_url": cb_url
                        }).to_string(),
                        "action_id": "warmplane_approve_btn"
                    },
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "❌ Reject",
                            "emoji": true
                        },
                        "style": "danger",
                        "value": json!({
                            "action": "reject",
                            "ticket_id": ticket_id,
                            "callback_url": cb_url
                        }).to_string(),
                        "action_id": "warmplane_reject_btn"
                    }
                ]
            }));
        }
    } else {
        let details_str = serde_json::to_string_pretty(data).unwrap_or_else(|_| "{}".to_string());
        blocks.push(json!({
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": format!("*Event Details:*\n```{}```", details_str)
            }
        }));
    }

    json!({
        "text": title,
        "blocks": blocks
    })
}

fn build_discord_payload(event_type: &str, data: &Value, callback_url: Option<&str>) -> Value {
    let (title, color) = match event_type {
        "approval.requested" => ("🚨 Warmplane: Human Approval Required", 0xF59E0B),
        "circuit_breaker.tripped" => ("⚠️ Warmplane: Circuit Breaker Tripped", 0xEF4444),
        "policy.violation" => ("🛡️ Warmplane: Security Policy Violation", 0xDC2626),
        _ => ("📢 Warmplane Alert", 0x3B82F6),
    };

    let mut fields = Vec::new();
    if event_type == "approval.requested" {
        let ticket_id = data.get("id").and_then(Value::as_str).unwrap_or("unknown");
        let cap_id = data
            .get("capability_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let server_id = data
            .get("server_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let args_str = data
            .get("sanitized_args")
            .or_else(|| data.get("args"))
            .map(|a| serde_json::to_string(a).unwrap_or_else(|_| "{}".to_string()))
            .unwrap_or_else(|| "{}".to_string());

        fields.push(
            json!({ "name": "Capability", "value": format!("`{}`", cap_id), "inline": true }),
        );
        fields
            .push(json!({ "name": "Server", "value": format!("`{}`", server_id), "inline": true }));
        fields.push(
            json!({ "name": "Ticket ID", "value": format!("`{}`", ticket_id), "inline": true }),
        );
        fields.push(json!({ "name": "Arguments", "value": format!("```json\n{}\n```", args_str), "inline": false }));
    }

    let embed = json!({
        "title": title,
        "color": color,
        "fields": fields,
        "footer": { "text": "Warmplane Control Plane" }
    });

    let mut payload = json!({
        "embeds": [embed]
    });

    if let Some(cb_url) = callback_url {
        if event_type == "approval.requested" {
            let ticket_id = data.get("id").and_then(Value::as_str).unwrap_or("unknown");
            payload["components"] = json!([
                {
                    "type": 1,
                    "components": [
                        {
                            "type": 2,
                            "style": 3,
                            "label": "Approve",
                            "custom_id": format!("approve:{}", ticket_id)
                        },
                        {
                            "type": 2,
                            "style": 4,
                            "label": "Reject",
                            "custom_id": format!("reject:{}", ticket_id)
                        },
                        {
                            "type": 2,
                            "style": 5,
                            "label": "Open Control Deck",
                            "url": cb_url
                        }
                    ]
                }
            ]);
        }
    }

    payload
}

fn build_teams_payload(event_type: &str, data: &Value, callback_url: Option<&str>) -> Value {
    let title = match event_type {
        "approval.requested" => "🚨 Warmplane: Human Approval Required",
        "circuit_breaker.tripped" => "⚠️ Warmplane: Circuit Breaker Tripped",
        _ => "📢 Warmplane Event",
    };

    let mut body = vec![json!({
        "type": "TextBlock",
        "size": "Medium",
        "weight": "Bolder",
        "text": title
    })];

    if event_type == "approval.requested" {
        let ticket_id = data.get("id").and_then(Value::as_str).unwrap_or("unknown");
        let cap_id = data
            .get("capability_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let server_id = data
            .get("server_id")
            .and_then(Value::as_str)
            .unwrap_or("unknown");

        body.push(json!({
            "type": "FactSet",
            "facts": [
                { "title": "Ticket ID", "value": ticket_id },
                { "title": "Capability", "value": cap_id },
                { "title": "Server", "value": server_id }
            ]
        }));
    }

    let mut card = json!({
        "type": "message",
        "attachments": [
            {
                "contentType": "application/vnd.microsoft.card.adaptive",
                "content": {
                    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                    "type": "AdaptiveCard",
                    "version": "1.4",
                    "body": body
                }
            }
        ]
    });

    if let Some(cb_url) = callback_url {
        if event_type == "approval.requested" {
            let ticket_id = data.get("id").and_then(Value::as_str).unwrap_or("unknown");
            card["attachments"][0]["content"]["actions"] = json!([
                {
                    "type": "Action.Submit",
                    "title": "Approve",
                    "data": {
                        "action": "approve",
                        "ticket_id": ticket_id
                    }
                },
                {
                    "type": "Action.Submit",
                    "title": "Reject",
                    "data": {
                        "action": "reject",
                        "ticket_id": ticket_id
                    }
                },
                {
                    "type": "Action.OpenUrl",
                    "title": "Open Control Deck",
                    "url": cb_url
                }
            ]);
        }
    }

    card
}

/// Verifies an HMAC-SHA256 signature for incoming webhook payloads.
pub fn verify_signature(
    secret: &str,
    body: &str,
    signature_header: &str,
    timestamp: Option<&str>,
) -> bool {
    let sig_to_check = if let Some(stripped) = signature_header.strip_prefix("sha256=") {
        stripped
    } else if let Some(stripped) = signature_header.strip_prefix("v0=") {
        stripped
    } else {
        signature_header
    };

    let expected_mac = match HmacSha256::new_from_slice(secret.as_bytes()) {
        Ok(mut mac) => {
            if let Some(ts) = timestamp {
                mac.update(format!("{}.{}", ts, body).as_bytes());
            } else {
                mac.update(body.as_bytes());
            }
            hex::encode(mac.finalize().into_bytes())
        }
        Err(_) => return false,
    };

    sig_to_check.eq_ignore_ascii_case(&expected_mac)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_slack_block_generation() {
        let data = json!({
            "id": "appr-123",
            "capability_id": "db.drop_database",
            "server_id": "production_db",
            "sanitized_args": { "db": "users" }
        });

        let payload = format_webhook_payload(
            WebhookFormat::Slack,
            "approval.requested",
            &data,
            Some("http://127.0.0.1:9090"),
        );

        assert!(payload.get("blocks").is_some());
        let blocks = payload["blocks"].as_array().unwrap();
        assert!(blocks.len() >= 3);
        assert_eq!(
            blocks[0]["text"]["text"],
            "🚨 Warmplane: Human Approval Required"
        );
    }

    #[test]
    fn test_signature_verification() {
        let secret = "super-secret-key-123";
        let body = r#"{"action":"approve","ticket_id":"appr-123"}"#;
        let ts = "1724700000";

        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(format!("{}.{}", ts, body).as_bytes());
        let valid_sig = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));

        assert!(verify_signature(secret, body, &valid_sig, Some(ts)));
        assert!(!verify_signature(secret, body, "sha256=invalid", Some(ts)));
    }
}