tandem-server 0.7.2

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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
// Copyright (c) 2026 Frumu LTD
// Licensed under the Business Source License 1.1

//! Discord interaction endpoint.
//!
//! Discord POSTs a payload here for every interaction (PING, button click,
//! modal submit, slash command). Body is JSON.
//!
//! Hard requirements (per Discord docs):
//! - Verify `x-signature-ed25519` and `x-signature-timestamp` on every
//!   request via `tandem_channels::signing::verify_discord_signature`.
//!   Discord disables the endpoint if even a single inbound interaction is
//!   unverified, so we must reject with HTTP 401 on every failure.
//! - Respond to PING (`type = 1`) with PONG (`type = 1`) — Discord uses this
//!   to validate the endpoint when first registered.
//! - Acknowledge any other interaction within 3 seconds. Button clicks land
//!   here, so we either dispatch synchronously and return an UPDATE_MESSAGE
//!   (`type = 7`) or return a deferred ack (`type = 6`) and PATCH the message
//!   later via the interaction webhook URL.
//! - Reject retries durably by tenant, application, interaction ID, and body
//!   digest before dispatching any side effect.

use std::time::{SystemTime, UNIX_EPOCH};

use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::{json, Value};
use tandem_channels::discord_blocks::{parse_custom_id, ParsedCustomId};
use tandem_channels::signing::verify_discord_signature;

use crate::app::rate_limit::{ChannelRateLimitKey, ChannelRateLimitKind};
use crate::app::state::channel_user_capabilities::{
    channel_requires_approval_step_up, channel_security_profile_from_config,
};
use crate::app::state::principals::channel_identity::{
    channel_bound_tenant, channel_is_open_to_all, resolve_channel_user, ChannelIdentityResolution,
    ChannelKind,
};
use crate::AppState;

mod replay;

use replay::{prepare_discord_interaction, DiscordReplayClaimPreparation};

const DISCORD_SIGNATURE_TIMESTAMP_TOLERANCE_SECS: u64 = 5 * 60;

/// Discord interaction handler. Wired at `POST /channels/discord/interactions`.
pub(crate) async fn discord_interactions(
    State(state): State<AppState>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let public_key = match read_discord_public_key(&state).await {
        Some(key) => key,
        None => return reject_unauthorized("discord public key not configured"),
    };

    let signature = headers
        .get("x-signature-ed25519")
        .and_then(|v| v.to_str().ok());
    let timestamp = headers
        .get("x-signature-timestamp")
        .and_then(|v| v.to_str().ok());
    let now_secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0);
    if !discord_timestamp_is_fresh(timestamp, now_secs) {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            "rejecting Discord interaction outside the signed timestamp window"
        );
        return reject_unauthorized("stale or invalid signature timestamp");
    }

    if let Err(error) = verify_discord_signature(&body, signature, timestamp, &public_key) {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            ?error,
            "rejecting unsigned/forged Discord interaction"
        );
        return reject_unauthorized(&error.to_string());
    }

    let payload: Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(err) => return reject_bad_request(&format!("payload is not JSON: {err}")),
    };

    let interaction_type = payload.get("type").and_then(Value::as_u64).unwrap_or(0);

    // Type 1: PING. Reply with PONG so Discord's endpoint-validation flow
    // can confirm the URL.
    if interaction_type == 1 {
        return Json(json!({ "type": 1 })).into_response();
    }

    let interaction_id = match bounded_discord_identifier(&payload, "id") {
        Some(value) => value,
        None => return reject_bad_request("payload missing a valid interaction id"),
    };
    let application_id = match bounded_discord_identifier(&payload, "application_id") {
        Some(value) => value,
        None => return reject_bad_request("payload missing a valid application id"),
    };
    match interaction_type {
        // 3: MESSAGE_COMPONENT — button clicks on action rows.
        3 => {
            handle_message_component(
                state,
                &payload,
                application_id,
                interaction_id,
                body.as_ref(),
                now_secs.saturating_mul(1000),
            )
            .await
        },
        // 5: MODAL_SUBMIT — rework reason was submitted.
        5 => {
            handle_modal_submit(
                state,
                &payload,
                application_id,
                interaction_id,
                body.as_ref(),
                now_secs.saturating_mul(1000),
            )
            .await
        },
        // 2: APPLICATION_COMMAND — slash commands. Future: /pending, /approve.
        2 => Json(json!({
            "type": 4,
            "data": { "content": "Slash commands land in W5. Use the buttons on approval cards for now." }
        }))
        .into_response(),
        other => {
            tracing::info!(
                target: "tandem_server::discord_interactions",
                interaction_type = other,
                "unhandled Discord interaction type"
            );
            Json(json!({ "type": 6 })).into_response()
        }
    }
}

fn discord_tenant_context(effective_config: &Value) -> tandem_types::TenantContext {
    channel_bound_tenant(effective_config, ChannelKind::Discord)
        .map(|(org_id, workspace_id)| {
            tandem_types::TenantContext::explicit_user_workspace(
                org_id,
                workspace_id,
                None,
                "discord",
            )
        })
        .unwrap_or_else(tandem_types::TenantContext::local_implicit)
}

async fn claim_rate_limited_authorized_discord_interaction(
    state: &AppState,
    tenant_context: &tandem_types::TenantContext,
    application_id: &str,
    interaction_id: &str,
    body: &[u8],
    now_ms: u64,
    rate_key: &ChannelRateLimitKey,
    profile: tandem_channels::config::ChannelSecurityProfile,
) -> Result<(), Response> {
    let pending = match prepare_discord_interaction(
        state,
        tenant_context,
        application_id,
        interaction_id,
        body,
        now_ms,
    )
    .await
    {
        Ok(DiscordReplayClaimPreparation::Pending(pending)) => pending,
        Ok(DiscordReplayClaimPreparation::Duplicate) => {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                interaction_id,
                "acknowledging duplicate Discord interaction without redispatch"
            );
            return Err(duplicate_discord_acknowledgement());
        }
        Ok(DiscordReplayClaimPreparation::Conflict) => {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                interaction_id,
                "rejecting conflicting Discord interaction replay"
            );
            return Err(reject_conflict("conflicting interaction replay"));
        }
        Err(error) => {
            tracing::error!(
                target: "tandem_server::discord_interactions",
                error = %error,
                tenant = %tenant_context.org_id,
                application_id,
                "Discord interaction replay claim failed closed"
            );
            return Err(reject_service_unavailable());
        }
    };

    let rate_decision = state
        .channel_rate_limiter
        .check(rate_key, ChannelRateLimitKind::Decision, profile)
        .await;
    if !rate_decision.allowed {
        return Err(reject_rate_limited(rate_decision.retry_after_secs));
    }
    if let Err(error) = pending.commit().await {
        tracing::error!(
            target: "tandem_server::discord_interactions",
            error = %error,
            tenant = %tenant_context.org_id,
            application_id,
            "Discord interaction replay claim failed closed"
        );
        return Err(reject_service_unavailable());
    }
    Ok(())
}
fn duplicate_discord_acknowledgement() -> Response {
    Json(json!({
        "type": 7,
        "data": {
            "content": "Already processed — refresh to see the latest state.",
            "embeds": [],
            "components": [],
        }
    }))
    .into_response()
}

async fn handle_message_component(
    state: AppState,
    payload: &Value,
    application_id: &str,
    interaction_id: &str,
    body: &[u8],
    now_ms: u64,
) -> Response {
    let custom_id = match payload.pointer("/data/custom_id").and_then(Value::as_str) {
        Some(id) => id,
        None => return reject_bad_request("button payload missing data.custom_id"),
    };

    let parsed = match parse_custom_id(custom_id) {
        Some(p) => p,
        None => return reject_bad_request(&format!("unrecognized custom_id: {custom_id}")),
    };

    let user_id = match payload
        .pointer("/member/user/id")
        .or_else(|| payload.pointer("/user/id"))
        .and_then(Value::as_str)
    {
        Some(id) => id.to_string(),
        None => return reject_bad_request("payload missing user identification"),
    };

    // CRITICAL: Authorize the user against the allowlist BEFORE dispatching.
    let effective_config = state.config.get_effective_value().await;
    match resolve_channel_user(&effective_config, ChannelKind::Discord, &user_id) {
        ChannelIdentityResolution::Resolved(_principal) => {
            // User is authorized; proceed to handle the action.
        }
        ChannelIdentityResolution::Denied { .. } => {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                user_id = %user_id,
                "rejecting Discord interaction from unauthorized user"
            );
            return reject_forbidden("user not in allowed_users");
        }
        ChannelIdentityResolution::ChannelNotConfigured(_) => {
            return reject_bad_request("discord channel not properly configured");
        }
    }
    let profile =
        channel_security_profile_from_config(&effective_config, ChannelKind::Discord.as_str());
    if !state
        .channel_user_can_approve(
            ChannelKind::Discord.as_str(),
            &user_id,
            profile,
            channel_is_open_to_all(&effective_config, ChannelKind::Discord),
            None,
        )
        .await
    {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            user_id = %user_id,
            "rejecting Discord interaction without approval capability"
        );
        return reject_forbidden("user lacks approval capability");
    }
    // GOV-B5b: on a channel that opts into step-up, an approval requires an active
    // per-identity step-up grant issued out-of-band by the control panel.
    if channel_requires_approval_step_up(&effective_config, ChannelKind::Discord.as_str())
        && !state
            .channel_step_up_active(ChannelKind::Discord.as_str(), &user_id, None)
            .await
    {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            user_id = %user_id,
            "rejecting Discord interaction without an active step-up"
        );
        return reject_forbidden("step-up required");
    }
    let rate_key = ChannelRateLimitKey {
        channel: ChannelKind::Discord.as_str().to_string(),
        user_id: user_id.clone(),
    };
    let tenant_context = discord_tenant_context(&effective_config);
    if let Err(response) = claim_rate_limited_authorized_discord_interaction(
        &state,
        &tenant_context,
        application_id,
        interaction_id,
        body,
        now_ms,
        &rate_key,
        profile,
    )
    .await
    {
        return response;
    }

    match parsed.action.as_str() {
        "approve" | "cancel" => dispatch_decision(state, parsed, &user_id, None).await,
        "rework" => {
            // Open the modal so the user can supply a reason. The modal's
            // custom_id encodes the run_id + node_id for the eventual
            // MODAL_SUBMIT handler.
            let modal_custom_id = format!("tdm-modal:rework:{}:{}", parsed.run_id, parsed.node_id);
            // We don't have the InteractiveCard here; build a minimal modal
            // inline. (W4-bonus: pass the original card through interaction
            // metadata once message lookups are wired.)
            Json(json!({
                "type": 9,
                "data": {
                    "title": "Rework feedback",
                    "custom_id": modal_custom_id,
                    "components": [{
                        "type": 1,
                        "components": [{
                            "type": 4,
                            "custom_id": "reason_input",
                            "label": "What should change?",
                            "style": 2,
                            "min_length": 1,
                            "max_length": 4000,
                            "required": true,
                        }]
                    }]
                }
            }))
            .into_response()
        }
        other => reject_bad_request(&format!("unknown action: {other}")),
    }
}

async fn handle_modal_submit(
    state: AppState,
    payload: &Value,
    application_id: &str,
    interaction_id: &str,
    body: &[u8],
    now_ms: u64,
) -> Response {
    let custom_id = match payload.pointer("/data/custom_id").and_then(Value::as_str) {
        Some(id) => id,
        None => return reject_bad_request("modal payload missing data.custom_id"),
    };

    // Modal custom_id format: `tdm-modal:rework:{run_id}:{node_id}`.
    let mut parts = custom_id.splitn(4, ':');
    let prefix = parts.next().unwrap_or("");
    let action = parts.next().unwrap_or("");
    let run_id = parts.next().unwrap_or("").to_string();
    let node_id = parts.next().unwrap_or("").to_string();

    if prefix != "tdm-modal" || action != "rework" || run_id.is_empty() || node_id.is_empty() {
        return reject_bad_request(&format!(
            "unrecognized or malformed modal custom_id: {custom_id}"
        ));
    }

    let reason_raw = payload
        .pointer("/data/components/0/components/0/value")
        .and_then(Value::as_str)
        .unwrap_or("")
        .trim();
    if reason_raw.len() > 4000 {
        return reject_bad_request("reason exceeds 4000 character limit");
    }
    let reason = reason_raw.to_string();

    let user_id = match payload
        .pointer("/member/user/id")
        .or_else(|| payload.pointer("/user/id"))
        .and_then(Value::as_str)
    {
        Some(id) => id.to_string(),
        None => return reject_bad_request("modal payload missing user identification"),
    };

    // CRITICAL: Authorize the user against the allowlist BEFORE dispatching.
    let effective_config = state.config.get_effective_value().await;
    match resolve_channel_user(&effective_config, ChannelKind::Discord, &user_id) {
        ChannelIdentityResolution::Resolved(_principal) => {
            // User is authorized; proceed to handle the modal submission.
        }
        ChannelIdentityResolution::Denied { .. } => {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                user_id = %user_id,
                "rejecting Discord modal submission from unauthorized user"
            );
            return reject_forbidden("user not in allowed_users");
        }
        ChannelIdentityResolution::ChannelNotConfigured(_) => {
            return reject_bad_request("discord channel not properly configured");
        }
    }
    let profile =
        channel_security_profile_from_config(&effective_config, ChannelKind::Discord.as_str());
    if !state
        .channel_user_can_approve(
            ChannelKind::Discord.as_str(),
            &user_id,
            profile,
            channel_is_open_to_all(&effective_config, ChannelKind::Discord),
            None,
        )
        .await
    {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            user_id = %user_id,
            "rejecting Discord modal submission without approval capability"
        );
        return reject_forbidden("user lacks approval capability");
    }
    // GOV-B5b: on a channel that opts into step-up, an approval requires an active
    // per-identity step-up grant issued out-of-band by the control panel.
    if channel_requires_approval_step_up(&effective_config, ChannelKind::Discord.as_str())
        && !state
            .channel_step_up_active(ChannelKind::Discord.as_str(), &user_id, None)
            .await
    {
        tracing::warn!(
            target: "tandem_server::discord_interactions",
            user_id = %user_id,
            "rejecting Discord interaction without an active step-up"
        );
        return reject_forbidden("step-up required");
    }
    let rate_key = ChannelRateLimitKey {
        channel: ChannelKind::Discord.as_str().to_string(),
        user_id: user_id.clone(),
    };
    let tenant_context = discord_tenant_context(&effective_config);
    if let Err(response) = claim_rate_limited_authorized_discord_interaction(
        &state,
        &tenant_context,
        application_id,
        interaction_id,
        body,
        now_ms,
        &rate_key,
        profile,
    )
    .await
    {
        return response;
    }

    dispatch_decision(
        state,
        ParsedCustomId {
            action: "rework".to_string(),
            run_id,
            node_id,
        },
        &user_id,
        if reason.is_empty() {
            None
        } else {
            Some(reason)
        },
    )
    .await
}

async fn dispatch_decision(
    state: AppState,
    parsed: ParsedCustomId,
    user_id: &str,
    reason: Option<String>,
) -> Response {
    let input = crate::http::routines_automations::AutomationV2GateDecisionInput {
        decision: parsed.action.clone(),
        reason,
        approval_request_id: None,
        transition_id: None,
    };
    let tenant_context = state
        .get_automation_v2_run(&parsed.run_id)
        .await
        .map(|run| run.tenant_context)
        .unwrap_or_else(tandem_types::TenantContext::local_implicit);
    // GOV-B5c: if this channel is bound to a tenant, refuse to act on a run that
    // belongs to a different tenant. An unbound channel (single-tenant/local) is
    // unaffected.
    let effective_config = state.config.get_effective_value().await;
    if let Some((org_id, workspace_id)) =
        channel_bound_tenant(&effective_config, ChannelKind::Discord)
    {
        if tenant_context.org_id != org_id || tenant_context.workspace_id != workspace_id {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                user_id = %user_id,
                "rejecting Discord interaction targeting a run outside the channel's bound tenant"
            );
            let channel_tenant = tandem_types::TenantContext::explicit_user_workspace(
                org_id,
                workspace_id,
                None,
                "discord",
            );
            if let Err(error) = crate::http::channel_interaction_audit::append_cross_tenant_denial(
                &state,
                "discord",
                user_id,
                &parsed.run_id,
                channel_tenant,
                &tenant_context,
            )
            .await
            {
                return reject_forbidden(&format!(
                    "channel denied; required denial receipt persistence failed: {error}"
                ));
            }
            return reject_forbidden("channel not bound to this run's tenant");
        }
    }
    // GOV-B1: caller is verified (Ed25519 signature + allowlist + Approve tier);
    // attribute the decision to the Discord identity as a human approver.
    let decider = crate::automation_v2::governance::GovernanceActorRef::human(
        Some(user_id.to_string()),
        "discord",
    );
    let result = crate::http::routines_automations::automations_v2_run_gate_decide_inner(
        state,
        tenant_context,
        None,
        parsed.run_id.clone(),
        input,
        decider,
    )
    .await;

    match result {
        Ok(_) => {
            tracing::info!(
                target: "tandem_server::discord_interactions",
                run_id = %parsed.run_id,
                user = %user_id,
                action = %parsed.action,
                "Discord interaction decided gate"
            );
            // Type 7: UPDATE_MESSAGE — rewrite the original message inline.
            // We send a minimal acknowledgment; the full edit (with colors,
            // footer, etc.) is best done by a follow-up PATCH using the
            // discord_blocks builders. For v1 we ack with a brief content
            // line and let the dispatcher's message-update task replace the
            // card if it owns the original message handle.
            Json(json!({
                "type": 7,
                "data": {
                    "content": format!("`{}` by <@{}>.", parsed.action, user_id),
                    "embeds": [],
                    "components": [],
                }
            }))
            .into_response()
        }
        Err((status, body)) => {
            tracing::warn!(
                target: "tandem_server::discord_interactions",
                run_id = %parsed.run_id,
                status = %status,
                body = %body.0,
                "gate-decide returned non-success"
            );
            // Discord treats anything > 200 as a failure that disables the
            // endpoint long-term. Map non-200 to a UPDATE_MESSAGE response
            // so Discord stays happy and the user sees the conflict.
            let winner = body
                .0
                .pointer("/winningDecision/decision")
                .and_then(Value::as_str)
                .unwrap_or("another operator");
            Json(json!({
                "type": 7,
                "data": {
                    "content": format!(
                        "Already decided ({}) — refresh to see the latest state.",
                        winner
                    ),
                    "embeds": [],
                    "components": [],
                }
            }))
            .into_response()
        }
    }
}

async fn read_discord_public_key(state: &AppState) -> Option<String> {
    let effective = state.config.get_effective_value().await;
    effective
        .pointer("/channels/discord/public_key")
        .and_then(Value::as_str)
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

fn bounded_discord_identifier<'a>(payload: &'a Value, field: &str) -> Option<&'a str> {
    payload
        .get(field)
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty() && value.len() <= 256 && value.is_ascii())
}

fn discord_timestamp_is_fresh(timestamp: Option<&str>, now_secs: u64) -> bool {
    timestamp
        .and_then(|value| value.parse::<u64>().ok())
        .is_some_and(|timestamp_secs| {
            now_secs.abs_diff(timestamp_secs) <= DISCORD_SIGNATURE_TIMESTAMP_TOLERANCE_SECS
        })
}

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

fn reject_conflict(reason: &str) -> Response {
    (
        StatusCode::CONFLICT,
        Json(json!({ "error": "Conflict", "reason": reason })),
    )
        .into_response()
}

fn reject_service_unavailable() -> Response {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(json!({
            "error": "ServiceUnavailable",
            "reason": "replay protection unavailable",
        })),
    )
        .into_response()
}

fn reject_forbidden(reason: &str) -> Response {
    (
        StatusCode::FORBIDDEN,
        Json(json!({
            "error": "Forbidden",
            "reason": reason,
        })),
    )
        .into_response()
}

fn reject_rate_limited(retry_after_secs: u64) -> Response {
    let mut response = (
        StatusCode::TOO_MANY_REQUESTS,
        Json(json!({ "error": "rate limit exceeded" })),
    )
        .into_response();
    if let Ok(value) = axum::http::HeaderValue::from_str(&retry_after_secs.max(1).to_string()) {
        response
            .headers_mut()
            .insert(axum::http::header::RETRY_AFTER, value);
    }
    response
}

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

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

    #[test]
    fn timestamp_freshness_accepts_only_the_five_minute_window() {
        let now = 1_000;
        assert!(discord_timestamp_is_fresh(Some("1000"), now));
        assert!(discord_timestamp_is_fresh(Some("700"), now));
        assert!(discord_timestamp_is_fresh(Some("1300"), now));
        assert!(!discord_timestamp_is_fresh(Some("699"), now));
        assert!(!discord_timestamp_is_fresh(Some("1301"), now));
        assert!(!discord_timestamp_is_fresh(Some("not-a-time"), now));
        assert!(!discord_timestamp_is_fresh(None, now));
    }

    /// Modal custom_id parsing handles the exact format `handle_modal_submit`
    /// produces. Keep this golden so the round-trip stays stable.
    #[test]
    fn modal_custom_id_format_is_recognizable() {
        let raw = "tdm-modal:rework:auto-v2-run-abc123:send_email";
        let mut parts = raw.splitn(4, ':');
        assert_eq!(parts.next(), Some("tdm-modal"));
        assert_eq!(parts.next(), Some("rework"));
        assert_eq!(parts.next(), Some("auto-v2-run-abc123"));
        assert_eq!(parts.next(), Some("send_email"));
    }
}