tandem-server 0.5.5

HTTP server for Tandem engine APIs
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
//! Slack interaction endpoint.
//!
//! Slack POSTs a payload here whenever a user clicks a button on a
//! Block Kit card, submits a modal, or invokes an interaction shortcut.
//! Slack's spec is `application/x-www-form-urlencoded` with one field
//! `payload` whose value is the JSON interaction body.
//!
//! Hard requirements (per Slack docs):
//! - Verify the request via HMAC-SHA256 over `v0:{timestamp}:{raw_body}`
//!   using the app signing secret. See [`tandem_channels::signing`].
//! - Reject any timestamp older than 5 minutes (replay protection).
//! - Acknowledge the request within 3 seconds. We do this synchronously by
//!   processing button clicks fast (gate-decide is in-memory) and returning
//!   200 with an empty body — Slack treats that as success and does not retry.
//! - Idempotent on retries: dedup by `(action_ts, action_id)` so accidental
//!   double-fires don't double-decide.
//!
//! Decision dispatch reuses `automations_v2_run_gate_decide` directly. The
//! shared `pause_for_gate` / `decide_gate` helpers from W1.3 will replace
//! that direct call when they land.

use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};

use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use axum::Json;
use serde_json::{json, Value};
use tandem_channels::signing::verify_slack_signature;

use crate::AppState;

/// Bounded LRU-ish dedup set for Slack interaction `(action_ts, action_id)`
/// pairs. Slack retries interactions if the 3-second ack is missed; this
/// prevents the second retry from double-decide-ing.
///
/// Cap is intentionally small — entries age out by FIFO once the cap is hit.
/// In a real production deployment this would be tenant-scoped and persisted;
/// for v1 in-memory dedup is sufficient because gate decisions are themselves
/// idempotent at the run level (the second call hits the 409 path with the
/// winner identity from W2.6).
const DEDUP_CAP: usize = 4096;

static SEEN_INTERACTIONS: OnceLock<Mutex<DedupRing>> = OnceLock::new();

fn dedup_ring() -> &'static Mutex<DedupRing> {
    SEEN_INTERACTIONS.get_or_init(|| Mutex::new(DedupRing::new()))
}

struct DedupRing {
    set: HashSet<String>,
    order: std::collections::VecDeque<String>,
}

impl DedupRing {
    fn new() -> Self {
        Self {
            set: HashSet::with_capacity(DEDUP_CAP),
            order: std::collections::VecDeque::with_capacity(DEDUP_CAP),
        }
    }

    /// Returns `true` if the key is new (and records it). Returns `false` if
    /// the key was already seen recently.
    fn record_new(&mut self, key: &str) -> bool {
        if self.set.contains(key) {
            return false;
        }
        if self.order.len() >= DEDUP_CAP {
            if let Some(oldest) = self.order.pop_front() {
                self.set.remove(&oldest);
            }
        }
        self.set.insert(key.to_string());
        self.order.push_back(key.to_string());
        true
    }
}

/// Slack interaction handler.
///
/// Wired at `POST /channels/slack/interactions`.
pub(crate) async fn slack_interactions(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let signing_secret = match read_slack_signing_secret(&state).await {
        Some(secret) => secret,
        None => return reject_unauthorized("slack signing secret not configured"),
    };

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

    let now = chrono::Utc::now().timestamp();
    if let Err(error) = verify_slack_signature(&body, signature, timestamp, &signing_secret, now) {
        tracing::warn!(target: "tandem_server::slack_interactions", ?error, "rejecting unsigned/forged Slack interaction");
        return reject_unauthorized(&error.to_string());
    }

    let payload = match parse_slack_interaction_body(&body) {
        Ok(payload) => payload,
        Err(reason) => return reject_bad_request(&reason),
    };

    let dedup_key = make_dedup_key(&payload);
    if let Some(key) = dedup_key.as_ref() {
        let mut guard = dedup_ring().lock().expect("dedup mutex poisoned");
        if !guard.record_new(key) {
            tracing::debug!(target: "tandem_server::slack_interactions", %key, "duplicate Slack interaction — already processed");
            return ok_empty();
        }
    }

    let action = match extract_primary_action(&payload) {
        Ok(action) => action,
        Err(reason) => return reject_bad_request(&reason),
    };

    let parsed_value = match parse_button_value(&action.value) {
        Ok(v) => v,
        Err(reason) => return reject_bad_request(&reason),
    };
    let Some(run_id) = parsed_value
        .pointer("/correlation/automation_v2_run_id")
        .and_then(Value::as_str)
        .map(|s| s.to_string())
    else {
        return reject_bad_request("button value missing automation_v2_run_id");
    };

    // Translate Slack action_id → gate-decide decision string.
    let decision = match action.action_id.as_str() {
        "approve" => "approve",
        "rework" => "rework",
        "cancel" => "cancel",
        other => return reject_bad_request(&format!("unknown action_id: {other}")),
    };

    // For W2.4 we dispatch the approve/cancel decisions directly. Rework
    // requires a reason and Slack passes the reason via a follow-up modal
    // submission — that round-trip lands in W2.5. For now we accept the
    // rework click but defer the decision until the modal is wired.
    if decision == "rework" {
        // Open the modal (the caller built it via slack_blocks::build_rework_modal_payload).
        // Until the modal POST handler lands in W2.5, return 200 with a hint.
        tracing::info!(
            target: "tandem_server::slack_interactions",
            run_id = %run_id,
            "rework button clicked; modal flow lands in W2.5"
        );
        return ok_empty();
    }

    let input = crate::http::routines_automations::AutomationV2GateDecisionInput {
        decision: decision.to_string(),
        reason: None,
    };

    let result = crate::http::routines_automations::automations_v2_run_gate_decide(
        State(state),
        axum::extract::Path(run_id.clone()),
        Json(input),
    )
    .await;

    match result {
        Ok(_) => {
            tracing::info!(
                target: "tandem_server::slack_interactions",
                run_id = %run_id,
                user = %action.user_id,
                decision,
                "Slack interaction decided gate"
            );
            ok_empty()
        }
        Err((status, body_json)) => {
            // Race UX: if we lost the race, surface "already decided by …"
            // back via the response. Slack will render the response_url
            // payload separately — for now, log + return the same status.
            tracing::warn!(
                target: "tandem_server::slack_interactions",
                run_id = %run_id,
                status = %status,
                body = %body_json.0,
                "gate-decide returned non-success"
            );
            // Slack treats anything > 200 as a retry trigger; map 409 to 200
            // with the body so Slack does not retry the (now-resolved) action.
            ok_with_payload(json!({
                "ok": false,
                "status": status.as_u16(),
                "body": body_json.0,
            }))
        }
    }
}

#[derive(Debug, Clone)]
struct PrimaryAction {
    action_id: String,
    value: String,
    user_id: String,
}

fn extract_primary_action(payload: &Value) -> Result<PrimaryAction, String> {
    let actions = payload
        .get("actions")
        .and_then(Value::as_array)
        .ok_or_else(|| "payload missing `actions` array".to_string())?;
    let first = actions
        .first()
        .ok_or_else(|| "actions array is empty".to_string())?;
    let action_id = first
        .get("action_id")
        .and_then(Value::as_str)
        .ok_or_else(|| "action missing action_id".to_string())?
        .to_string();
    let value = first
        .get("value")
        .and_then(Value::as_str)
        .ok_or_else(|| "action missing value".to_string())?
        .to_string();
    let user_id = payload
        .pointer("/user/id")
        .and_then(Value::as_str)
        .unwrap_or("unknown")
        .to_string();
    Ok(PrimaryAction {
        action_id,
        value,
        user_id,
    })
}

fn parse_button_value(raw: &str) -> Result<Value, String> {
    serde_json::from_str(raw).map_err(|err| format!("button value is not JSON: {err}"))
}

fn make_dedup_key(payload: &Value) -> Option<String> {
    let action_ts = payload
        .pointer("/actions/0/action_ts")
        .and_then(Value::as_str)?;
    let action_id = payload
        .pointer("/actions/0/action_id")
        .and_then(Value::as_str)?;
    Some(format!("{action_ts}:{action_id}"))
}

/// Parse Slack's `application/x-www-form-urlencoded` body. Slack sends the
/// interaction JSON as the value of a single `payload` field.
fn parse_slack_interaction_body(body: &[u8]) -> Result<Value, String> {
    let body_str = std::str::from_utf8(body).map_err(|_| "body is not utf-8".to_string())?;
    for pair in body_str.split('&') {
        let mut parts = pair.splitn(2, '=');
        let key = parts.next().unwrap_or("");
        let value = parts.next().unwrap_or("");
        if key == "payload" {
            let decoded = url_decode(value);
            return serde_json::from_str(&decoded)
                .map_err(|err| format!("payload field is not valid JSON: {err}"));
        }
    }
    Err("body did not contain a `payload` form field".to_string())
}

fn url_decode(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let hi = hex_digit(bytes[i + 1]);
                let lo = hex_digit(bytes[i + 2]);
                if let (Some(hi), Some(lo)) = (hi, lo) {
                    out.push((hi << 4 | lo) as char);
                    i += 3;
                } else {
                    out.push('%');
                    i += 1;
                }
            }
            other => {
                out.push(other as char);
                i += 1;
            }
        }
    }
    out
}

fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

fn reject_unauthorized(reason: &str) -> Response {
    (
        StatusCode::UNAUTHORIZED,
        Json(json!({
            "error": "Unauthorized",
            "reason": reason,
        })),
    )
        .into_response()
}

fn reject_bad_request(reason: &str) -> Response {
    (
        StatusCode::BAD_REQUEST,
        Json(json!({
            "error": "BadRequest",
            "reason": reason,
        })),
    )
        .into_response()
}

fn ok_empty() -> Response {
    (StatusCode::OK, Json(json!({}))).into_response()
}

fn ok_with_payload(value: Value) -> Response {
    (StatusCode::OK, Json(value)).into_response()
}

use axum::response::IntoResponse;

/// Read the configured Slack signing secret from `state.config`. Returns
/// `None` when the channel is not configured or the secret field is empty —
/// either case must be treated as "interactions are not enabled," not as a
/// silent allow.
async fn read_slack_signing_secret(state: &AppState) -> Option<String> {
    let effective = state.config.get_effective_value().await;
    effective
        .pointer("/channels/slack/signing_secret")
        .and_then(Value::as_str)
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

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

    #[test]
    fn url_decode_handles_basic_pct_encodings() {
        assert_eq!(url_decode("hello%20world"), "hello world");
        assert_eq!(url_decode("a+b"), "a b");
        assert_eq!(url_decode("%7B%7D"), "{}");
    }

    #[test]
    fn parse_slack_interaction_body_extracts_payload_field() {
        let body = "payload=%7B%22type%22%3A%22block_actions%22%7D";
        let parsed = parse_slack_interaction_body(body.as_bytes()).expect("parsed");
        assert_eq!(
            parsed.get("type").and_then(Value::as_str),
            Some("block_actions")
        );
    }

    #[test]
    fn parse_slack_interaction_body_rejects_missing_payload() {
        let body = "team_id=T123&user_id=U456";
        let err = parse_slack_interaction_body(body.as_bytes()).unwrap_err();
        assert!(err.contains("payload"));
    }

    #[test]
    fn extract_primary_action_returns_first_button() {
        let payload = json!({
            "actions": [
                { "action_id": "approve", "value": "{\"x\":1}" },
                { "action_id": "rework", "value": "{}" }
            ],
            "user": { "id": "U999" }
        });
        let action = extract_primary_action(&payload).expect("action");
        assert_eq!(action.action_id, "approve");
        assert_eq!(action.value, "{\"x\":1}");
        assert_eq!(action.user_id, "U999");
    }

    #[test]
    fn make_dedup_key_uses_action_ts_and_action_id() {
        let payload = json!({
            "actions": [{ "action_id": "approve", "action_ts": "1700000000.0001" }]
        });
        let key = make_dedup_key(&payload).expect("key");
        assert_eq!(key, "1700000000.0001:approve");
    }

    #[test]
    fn dedup_ring_returns_false_on_repeat() {
        let mut ring = DedupRing::new();
        assert!(ring.record_new("a"));
        assert!(!ring.record_new("a"));
        assert!(ring.record_new("b"));
    }

    #[test]
    fn dedup_ring_evicts_oldest_at_cap() {
        let mut ring = DedupRing::new();
        for i in 0..DEDUP_CAP {
            ring.record_new(&format!("k{i}"));
        }
        assert!(!ring.record_new("k0"));
        ring.record_new(&format!("k{DEDUP_CAP}"));
        // After overflow, "k0" is still in the ring (record_new returned false)
        // but inserting a brand new key past the cap should evict "k0".
        assert!(ring.record_new("k0_again_after_evict"));
    }
}