warmplane 0.30.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Rust guideline compliant 2026-08-26

//! REST API endpoints for incoming ChatOps callbacks and webhook simulation.

use axum::{
    body::Bytes,
    extract::State,
    http::{HeaderMap, StatusCode},
    response::IntoResponse,
    Json,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tracing::{info, warn};

use crate::daemon::AppState;

/// Request payload for simulating a test webhook dispatch.
#[derive(Deserialize, Debug, Clone)]
pub struct TestWebhookRequest {
    /// Target webhook URL override (optional).
    #[serde(default)]
    pub url: Option<String>,
    /// Payload format override (optional).
    #[serde(default)]
    pub format: Option<crate::chatops::WebhookFormat>,
}

/// Generic callback payload structure.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct GenericCallbackPayload {
    /// Action type (`approve` or `reject`).
    pub action: String,
    /// Approval ticket ID.
    pub ticket_id: String,
    /// Operator identifier.
    #[serde(default)]
    pub operator: Option<String>,
    /// Reason if rejected.
    #[serde(default)]
    pub reason: Option<String>,
    /// Modified JSON arguments if approved with edits.
    #[serde(default)]
    pub modified_args: Option<Value>,
}

/// Handles POST `/v1/webhooks/callbacks` processing incoming decisions from Slack, Discord, or generic webhooks.
pub async fn handle_webhook_callback(
    State(state): State<AppState>,
    headers: HeaderMap,
    body_bytes: Bytes,
) -> impl IntoResponse {
    let body_str = match std::str::from_utf8(&body_bytes) {
        Ok(s) => s,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "ok": false, "error": "Invalid UTF-8 payload" })),
            )
                .into_response()
        }
    };

    // Load active config to check secret
    let config = crate::config::load_or_default_config(&state.config_path).unwrap_or_default();
    if let Some(ref policy) = config.policy {
        if let Some(ref webhook_cfg) = policy.webhook {
            if let Some(secret) = webhook_cfg.resolve_secret() {
                let sig_header = headers
                    .get("x-warmplane-signature")
                    .or_else(|| headers.get("x-slack-signature"))
                    .and_then(|v| v.to_str().ok());

                let ts_header = headers
                    .get("x-warmplane-timestamp")
                    .or_else(|| headers.get("x-slack-request-timestamp"))
                    .and_then(|v| v.to_str().ok());

                if let Some(sig) = sig_header {
                    if !crate::chatops::verify_signature(&secret, body_str, sig, ts_header) {
                        warn!("Rejecting incoming webhook callback: HMAC signature mismatch");
                        return (
                            StatusCode::UNAUTHORIZED,
                            Json(json!({ "ok": false, "error": "Signature mismatch" })),
                        )
                            .into_response();
                    }
                }
            }
        }
    }

    // Try parsing as Slack URL-encoded payload first (`payload=...`)
    let (action, ticket_id, operator, reason, modified_args) =
        if let Some(raw_payload) = body_str.strip_prefix("payload=") {
            let decoded = url_decode_str(raw_payload);
            if let Ok(slack_val) = serde_json::from_str::<Value>(&decoded) {
                parse_slack_interaction(&slack_val)
            } else {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "ok": false, "error": "Invalid Slack payload JSON" })),
                )
                    .into_response();
            }
        } else if let Ok(generic_val) = serde_json::from_str::<GenericCallbackPayload>(body_str) {
            (
                generic_val.action,
                generic_val.ticket_id,
                generic_val
                    .operator
                    .unwrap_or_else(|| "chatops-operator".to_string()),
                generic_val.reason,
                generic_val.modified_args,
            )
        } else {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "ok": false, "error": "Unrecognized callback payload structure" })),
            )
                .into_response();
        };

    if action == "approve" {
        match state
            .approval_registry
            .approve(&ticket_id, operator.clone(), modified_args, None)
            .await
        {
            Ok(true) => {
                info!(ticket_id = %ticket_id, operator = %operator, "approved ticket via incoming webhook callback");
                (
                    StatusCode::OK,
                    Json(json!({
                        "ok": true,
                        "status": "approved",
                        "ticket_id": ticket_id,
                        "operator": operator,
                        "text": format!("✅ Approval ticket `{}` was successfully approved by `{}`.", ticket_id, operator)
                    })),
                )
                    .into_response()
            }
            Ok(false) => (
                StatusCode::NOT_FOUND,
                Json(json!({ "ok": false, "error": "Ticket not found or already resolved" })),
            )
                .into_response(),
            Err(e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "ok": false, "error": e.to_string() })),
            )
                .into_response(),
        }
    } else if action == "reject" {
        match state
            .approval_registry
            .reject(&ticket_id, operator.clone(), reason.clone(), None)
            .await
        {
            Ok(true) => {
                info!(ticket_id = %ticket_id, operator = %operator, "rejected ticket via incoming webhook callback");
                (
                    StatusCode::OK,
                    Json(json!({
                        "ok": true,
                        "status": "rejected",
                        "ticket_id": ticket_id,
                        "operator": operator,
                        "reason": reason,
                        "text": format!("❌ Approval ticket `{}` was rejected by `{}`.", ticket_id, operator)
                    })),
                )
                    .into_response()
            }
            Ok(false) => (
                StatusCode::NOT_FOUND,
                Json(json!({ "ok": false, "error": "Ticket not found or already resolved" })),
            )
                .into_response(),
            Err(e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "ok": false, "error": e.to_string() })),
            )
                .into_response(),
        }
    } else {
        (
            StatusCode::BAD_REQUEST,
            Json(json!({ "ok": false, "error": format!("Unsupported action '{}'", action) })),
        )
            .into_response()
    }
}

fn parse_slack_interaction(val: &Value) -> (String, String, String, Option<String>, Option<Value>) {
    let operator = val
        .get("user")
        .and_then(|u| u.get("username").or_else(|| u.get("name")))
        .and_then(Value::as_str)
        .unwrap_or("slack-user")
        .to_string();

    let mut action = "unknown".to_string();
    let mut ticket_id = "unknown".to_string();

    if let Some(actions) = val.get("actions").and_then(Value::as_array) {
        if let Some(first) = actions.first() {
            let action_id = first.get("action_id").and_then(Value::as_str).unwrap_or("");
            if action_id.contains("approve") {
                action = "approve".to_string();
            } else if action_id.contains("reject") {
                action = "reject".to_string();
            }

            if let Some(val_str) = first.get("value").and_then(Value::as_str) {
                if let Ok(parsed_btn_val) = serde_json::from_str::<Value>(val_str) {
                    if let Some(t_id) = parsed_btn_val.get("ticket_id").and_then(Value::as_str) {
                        ticket_id = t_id.to_string();
                    }
                    if let Some(act) = parsed_btn_val.get("action").and_then(Value::as_str) {
                        action = act.to_string();
                    }
                } else {
                    ticket_id = val_str.to_string();
                }
            }
        }
    }

    (action, ticket_id, operator, None, None)
}

fn url_decode_str(input: &str) -> String {
    let mut result = Vec::new();
    let mut bytes = input.bytes();
    while let Some(b) = bytes.next() {
        match b {
            b'+' => result.push(b' '),
            b'%' => {
                let h1 = bytes.next();
                let h2 = bytes.next();
                if let (Some(h1), Some(h2)) = (h1, h2) {
                    if let Ok(hex_byte) =
                        u8::from_str_radix(&format!("{}{}", h1 as char, h2 as char), 16)
                    {
                        result.push(hex_byte);
                        continue;
                    }
                }
                result.push(b'%');
                if let Some(h1) = h1 {
                    result.push(h1);
                }
                if let Some(h2) = h2 {
                    result.push(h2);
                }
            }
            other => result.push(other),
        }
    }
    String::from_utf8_lossy(&result).into_owned()
}

/// Handles POST `/v1/webhooks/test` sending a simulated test event to the configured webhook endpoint.
pub async fn handle_test_webhook(
    State(state): State<AppState>,
    Json(payload): Json<TestWebhookRequest>,
) -> impl IntoResponse {
    let config = crate::config::load_or_default_config(&state.config_path).unwrap_or_default();
    let webhook_cfg = if let Some(ref pol) = config.policy {
        pol.webhook.clone()
    } else {
        None
    };

    let target_url = payload
        .url
        .or_else(|| webhook_cfg.as_ref().map(|w| w.url.clone()));
    let target_format = payload
        .format
        .or_else(|| webhook_cfg.as_ref().and_then(|w| w.format))
        .unwrap_or_default();

    let target_url = match target_url {
        Some(u) if !u.trim().is_empty() => u,
        _ => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "ok": false, "error": "No webhook URL configured or provided" })),
            )
                .into_response();
        }
    };

    // Validate incoming URL syntax and scheme first
    let _ = match reqwest::Url::parse(&target_url) {
        Ok(u) => {
            if u.scheme() != "http" && u.scheme() != "https" {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({ "ok": false, "error": "Webhook URL must use http or https scheme" })),
                )
                    .into_response();
            }
            u
        }
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "ok": false, "error": format!("Invalid webhook URL: {}", e) })),
            )
                .into_response();
        }
    };

    // Verify target_url against configured webhook URL or explicit allowedUrls allowlist,
    // selecting the destination directly from the trusted configuration to break taint flow.
    let trusted_target_url = match webhook_cfg.as_ref() {
        Some(cfg) if cfg.url == target_url => cfg.url.as_str(),
        Some(cfg) => {
            if let Some(matched) = cfg
                .allowed_urls
                .iter()
                .find(|allowed| *allowed == &target_url)
            {
                matched.as_str()
            } else {
                return (
                    StatusCode::FORBIDDEN,
                    Json(json!({
                        "ok": false,
                        "error": "Webhook URL is not permitted. URL must match policy.webhook.url or be present in policy.webhook.allowed_urls."
                    })),
                )
                    .into_response();
            }
        }
        None => {
            return (
                StatusCode::FORBIDDEN,
                Json(json!({
                    "ok": false,
                    "error": "No policy webhook configuration present."
                })),
            )
                .into_response();
        }
    };

    // Parse the trusted URL into reqwest::Url
    let parsed_trusted_url = match reqwest::Url::parse(trusted_target_url) {
        Ok(u) => u,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({ "ok": false, "error": format!("Invalid webhook URL in configuration: {}", e) })),
            )
                .into_response();
        }
    };

    let test_data = json!({
        "id": "appr-test-101",
        "capability_id": "db.drop_database",
        "server_id": "postgres_production",
        "sanitized_args": {
            "database": "customer_data",
            "cascade": true
        },
        "request_id": "req-test-sim",
        "created_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(),
        "expires_at": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() + 300,
        "status": "pending"
    });

    let formatted = crate::chatops::format_webhook_payload(
        target_format,
        "approval.requested",
        &test_data,
        Some("http://127.0.0.1:9090"),
    );

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()
        .unwrap_or_default();

    match client.post(parsed_trusted_url).json(&formatted).send().await {
        Ok(resp) if resp.status().is_success() => (
            StatusCode::OK,
            Json(json!({
                "ok": true,
                "message": format!("Successfully sent test webhook ({:?}) to {}", target_format, target_url),
                "status_code": resp.status().as_u16(),
            })),
        )
            .into_response(),
        Ok(resp) => (
            StatusCode::BAD_GATEWAY,
            Json(json!({
                "ok": false,
                "error": format!("Webhook target responded with HTTP {}", resp.status()),
                "status_code": resp.status().as_u16(),
            })),
        )
            .into_response(),
        Err(e) => (
            StatusCode::BAD_GATEWAY,
            Json(json!({
                "ok": false,
                "error": format!("Failed to send test webhook: {}", e),
            })),
        )
            .into_response(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{McpConfig, PolicyConfig, WebhookConfig};
    use axum::body::to_bytes;
    use tempfile::NamedTempFile;

    #[tokio::test]
    async fn test_webhook_rejects_unpermitted_url() {
        let temp = NamedTempFile::new().unwrap();
        let config = McpConfig {
            policy: Some(PolicyConfig {
                webhook: Some(WebhookConfig {
                    url: "https://hooks.slack.com/services/T00/B00/X00".to_string(),
                    allowed_urls: vec!["https://discord.com/api/webhooks/1/2".to_string()],
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        std::fs::write(temp.path(), serde_json::to_string(&config).unwrap()).unwrap();

        let state = AppState::builder()
            .config_path(temp.path().to_str().unwrap().to_string())
            .catalog_version("test")
            .build();

        // 1. Target URL not in allowed list
        let req = TestWebhookRequest {
            url: Some("https://evil.internal.attacker.com/webhook".to_string()),
            format: None,
        };
        let resp = handle_test_webhook(State(state.clone()), Json(req))
            .await
            .into_response();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        let body_bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let body_json: Value = serde_json::from_slice(&body_bytes).unwrap();
        assert_eq!(body_json["ok"], false);

        // 2. Target URL with invalid non-http/https scheme
        let req_invalid = TestWebhookRequest {
            url: Some("file:///etc/passwd".to_string()),
            format: None,
        };
        let resp_invalid = handle_test_webhook(State(state), Json(req_invalid))
            .await
            .into_response();
        assert_eq!(resp_invalid.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_webhook_rejects_when_no_webhook_configured() {
        let temp = NamedTempFile::new().unwrap();
        let config = McpConfig::default();
        std::fs::write(temp.path(), serde_json::to_string(&config).unwrap()).unwrap();

        let state = AppState::builder()
            .config_path(temp.path().to_str().unwrap().to_string())
            .catalog_version("test")
            .build();

        let req = TestWebhookRequest {
            url: None,
            format: None,
        };
        let resp = handle_test_webhook(State(state), Json(req))
            .await
            .into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }
}