autumn-web 0.5.0

An opinionated, convention-over-configuration web framework for Rust
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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use autumn_web::config::{AutumnConfig, MockEnv};
use autumn_web::prelude::*;
use autumn_web::security::{CsrfConfig, SecurityConfig};
use autumn_web::test::{TestApp, TestResponse};
use autumn_web::webhook::{
    InMemoryWebhookReplayStore, SignedWebhook, WebhookEndpointConfig, WebhookProvider,
    WebhookRegistry, WebhookReplayBackend, WebhookReplayFuture, WebhookReplayStore,
    WebhookReplayStoreError, hmac_sha256_hex,
};
use serde_json::json;

static HANDLER_CALLS: AtomicUsize = AtomicUsize::new(0);
static TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

const CURRENT_SECRET: &str = "current-webhook-secret-32-bytes!!";
const PREVIOUS_SECRET: &str = "previous-webhook-secret-32-bytes!";

#[derive(Debug)]
struct UnavailableReplayStore;

impl WebhookReplayStore for UnavailableReplayStore {
    fn check_and_insert<'a>(
        &'a self,
        _key: &'a str,
        _received_at: SystemTime,
        _window: Duration,
    ) -> WebhookReplayFuture<'a> {
        Box::pin(async {
            Err(WebhookReplayStoreError::new(
                "custom replay backend offline",
            ))
        })
    }

    fn remove<'a>(&'a self, _key: &'a str) -> WebhookReplayFuture<'a> {
        Box::pin(async {
            Err(WebhookReplayStoreError::new(
                "custom replay backend offline",
            ))
        })
    }
}

#[post("/webhooks/stripe")]
async fn stripe_webhook(webhook: SignedWebhook) -> Json<serde_json::Value> {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    Json(json!({
        "provider": webhook.provider(),
        "delivery_id": webhook.delivery_id(),
        "event_type": webhook.event_type(),
        "raw": String::from_utf8_lossy(webhook.raw_body()),
    }))
}

#[post("/webhooks/github")]
async fn github_webhook(webhook: SignedWebhook) -> Json<serde_json::Value> {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    Json(json!({
        "provider": webhook.provider(),
        "delivery_id": webhook.delivery_id(),
        "event_type": webhook.event_type(),
    }))
}

#[post("/webhooks/slack")]
async fn slack_webhook(webhook: SignedWebhook) -> Json<serde_json::Value> {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    Json(json!({
        "provider": webhook.provider(),
        "delivery_id": webhook.delivery_id(),
        "event_type": webhook.event_type(),
    }))
}

#[post("/webhooks/generic")]
async fn generic_webhook(webhook: SignedWebhook) -> Json<serde_json::Value> {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    Json(json!({
        "provider": webhook.provider(),
        "delivery_id": webhook.delivery_id(),
        "event_type": webhook.event_type(),
    }))
}

fn unix_now() -> i64 {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system clock must be after unix epoch")
        .as_secs();
    i64::try_from(secs).expect("current unix timestamp fits in i64")
}

fn webhook_config(endpoints: Vec<WebhookEndpointConfig>) -> AutumnConfig {
    AutumnConfig {
        profile: Some("test".to_owned()),
        security: SecurityConfig {
            csrf: CsrfConfig {
                enabled: false,
                ..Default::default()
            },
            webhooks: autumn_web::webhook::WebhookConfig {
                endpoints,
                ..Default::default()
            },
            ..Default::default()
        },
        ..Default::default()
    }
}

fn client(endpoints: Vec<WebhookEndpointConfig>) -> autumn_web::test::TestClient {
    TestApp::new()
        .config(webhook_config(endpoints))
        .routes(routes![
            stripe_webhook,
            github_webhook,
            slack_webhook,
            generic_webhook
        ])
        .build()
}

fn client_with_registry(registry: WebhookRegistry) -> autumn_web::test::TestClient {
    let state = autumn_web::AppState::for_test().with_extension(registry);
    let mut route_defs = routes![github_webhook];
    let route = route_defs.remove(0);
    let router = axum::Router::new()
        .route(route.path, route.handler)
        .with_state(state.clone());
    TestApp::from_router(router, state)
}

fn endpoint(
    provider: WebhookProvider,
    path: &'static str,
    name: &'static str,
) -> WebhookEndpointConfig {
    WebhookEndpointConfig::new(name, path, provider, CURRENT_SECRET)
        .with_previous_secret(PREVIOUS_SECRET)
        .with_timestamp_tolerance_secs(300)
        .with_replay_window_secs(300)
}

fn stripe_signature(secret: &str, timestamp: i64, body: &[u8]) -> String {
    let mut signed_payload = timestamp.to_string().into_bytes();
    signed_payload.push(b'.');
    signed_payload.extend_from_slice(body);
    let signature = hmac_sha256_hex(secret.as_bytes(), &signed_payload);
    format!("t={timestamp},v1={signature}")
}

fn github_signature(secret: &str, body: &[u8]) -> String {
    format!("sha256={}", hmac_sha256_hex(secret.as_bytes(), body))
}

fn slack_signature(secret: &str, timestamp: i64, body: &[u8]) -> String {
    let timestamp = timestamp.to_string();
    let mut signed_payload = Vec::with_capacity(3 + timestamp.len() + 1 + body.len());
    signed_payload.extend_from_slice(b"v0:");
    signed_payload.extend_from_slice(timestamp.as_bytes());
    signed_payload.push(b':');
    signed_payload.extend_from_slice(body);
    format!("v0={}", hmac_sha256_hex(secret.as_bytes(), &signed_payload))
}

fn generic_signature(secret: &str, body: &[u8]) -> String {
    format!("sha256={}", hmac_sha256_hex(secret.as_bytes(), body))
}

fn problem_json(response: &TestResponse, status: u16) -> serde_json::Value {
    response.assert_status(status);
    response.assert_header_contains("content-type", "application/problem+json");
    let json: serde_json::Value = response.json();
    assert_eq!(json["status"], status);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| !detail.is_empty()),
        "Problem+JSON response should include a detail message"
    );
    assert!(
        json["instance"].as_str().is_some(),
        "Problem+JSON response should include an instance path"
    );
    assert!(
        json["request_id"].as_str().is_some(),
        "Problem+JSON response should include a request_id"
    );
    json
}

fn assert_duplicate_path_error(error: impl std::fmt::Display) {
    let message = error.to_string();
    assert!(
        message.contains("duplicate")
            && message.contains("/webhooks/duplicate")
            && message.contains("stripe")
            && message.contains("github"),
        "duplicate path error should identify both endpoints and the shared path, got: {message}"
    );
}

#[tokio::test(flavor = "current_thread")]
async fn provider_presets_verify_valid_requests_and_expose_metadata() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![
        endpoint(WebhookProvider::Stripe, "/webhooks/stripe", "stripe"),
        endpoint(WebhookProvider::Github, "/webhooks/github", "github"),
        endpoint(WebhookProvider::Slack, "/webhooks/slack", "slack"),
        endpoint(WebhookProvider::Generic, "/webhooks/generic", "generic"),
    ]);
    let now = unix_now();

    let stripe_body = br#"{"id":"evt_123","type":"invoice.paid"}"#;
    let response = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature(CURRENT_SECRET, now, stripe_body),
        )
        .body(stripe_body.as_slice())
        .send()
        .await;
    response.assert_ok();
    let stripe: serde_json::Value = response.json();
    assert_eq!(stripe["provider"], "stripe");
    assert_eq!(stripe["delivery_id"], "evt_123");
    assert_eq!(stripe["event_type"], "invoice.paid");
    assert_eq!(stripe["raw"], r#"{"id":"evt_123","type":"invoice.paid"}"#);

    let github_body = br#"{"action":"opened"}"#;
    let response = client
        .post("/webhooks/github")
        .header(
            "x-hub-signature-256",
            &github_signature(CURRENT_SECRET, github_body),
        )
        .header("x-github-delivery", "gh-delivery-1")
        .header("x-github-event", "pull_request")
        .body(github_body.as_slice())
        .send()
        .await;
    response.assert_ok();
    let github: serde_json::Value = response.json();
    assert_eq!(github["provider"], "github");
    assert_eq!(github["delivery_id"], "gh-delivery-1");
    assert_eq!(github["event_type"], "pull_request");

    let slack_body = br#"{"type":"event_callback","event":{"type":"message"},"event_id":"Ev-provider-preset","event_time":1234567890}"#;
    let response = client
        .post("/webhooks/slack")
        .header("content-type", "application/json")
        .header("x-slack-request-timestamp", &now.to_string())
        .header(
            "x-slack-signature",
            &slack_signature(CURRENT_SECRET, now, slack_body),
        )
        .body(slack_body.as_slice())
        .send()
        .await;
    response.assert_ok();
    let slack: serde_json::Value = response.json();
    assert_eq!(slack["provider"], "slack");
    assert_eq!(slack["delivery_id"], "Ev-provider-preset");
    assert_eq!(slack["event_type"], "event_callback");

    let generic_body = br#"{"kind":"cms.updated"}"#;
    let response = client
        .post("/webhooks/generic")
        .header(
            "x-webhook-signature",
            &generic_signature(CURRENT_SECRET, generic_body),
        )
        .header("x-webhook-delivery", "generic-delivery-1")
        .header("x-webhook-event", "cms.updated")
        .body(generic_body.as_slice())
        .send()
        .await;
    response.assert_ok();
    let generic: serde_json::Value = response.json();
    assert_eq!(generic["provider"], "generic");
    assert_eq!(generic["delivery_id"], "generic-delivery-1");
    assert_eq!(generic["event_type"], "cms.updated");

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 4);
}

#[tokio::test(flavor = "current_thread")]
async fn slack_events_api_json_body_uses_event_id_for_replay_protection() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Slack,
        "/webhooks/slack",
        "slack",
    )]);
    let now = unix_now();
    let body = br#"{"type":"event_callback","event":{"type":"app_mention"},"event_id":"Ev123ABC456","event_time":1234567890}"#;
    let signature = slack_signature(CURRENT_SECRET, now, body);

    let first = client
        .post("/webhooks/slack")
        .header("content-type", "application/json")
        .header("x-slack-request-timestamp", &now.to_string())
        .header("x-slack-signature", &signature)
        .body(body.as_slice())
        .send()
        .await;
    first.assert_ok();
    let json: serde_json::Value = first.json();
    assert_eq!(json["provider"], "slack");
    assert_eq!(json["delivery_id"], "Ev123ABC456");
    assert_eq!(json["event_type"], "event_callback");

    let second = client
        .post("/webhooks/slack")
        .header("content-type", "application/json")
        .header("x-slack-request-timestamp", &now.to_string())
        .header("x-slack-signature", &signature)
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&second, 409);
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn slack_url_verification_json_body_uses_challenge_as_replay_id() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Slack,
        "/webhooks/slack",
        "slack",
    )]);
    let now = unix_now();
    let body =
        br#"{"token":"deprecated-token","challenge":"challenge-123","type":"url_verification"}"#;

    let response = client
        .post("/webhooks/slack")
        .header("content-type", "application/json")
        .header("x-slack-request-timestamp", &now.to_string())
        .header(
            "x-slack-signature",
            &slack_signature(CURRENT_SECRET, now, body),
        )
        .body(body.as_slice())
        .send()
        .await;
    response.assert_ok();
    let json: serde_json::Value = response.json();
    assert_eq!(json["provider"], "slack");
    assert_eq!(json["delivery_id"], "challenge-123");
    assert_eq!(json["event_type"], "url_verification");
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[test]
fn duplicate_webhook_paths_are_rejected_before_registry_construction() {
    let config = webhook_config(vec![
        endpoint(WebhookProvider::Stripe, "/webhooks/duplicate", "stripe"),
        endpoint(WebhookProvider::Github, "/webhooks/duplicate", "github"),
    ]);

    let error = config
        .validate()
        .expect_err("duplicate webhook paths must fail app config validation");
    assert_duplicate_path_error(error);

    let error = WebhookRegistry::from_config(&config.security.webhooks)
        .expect_err("duplicate webhook paths must fail direct registry construction");
    assert_duplicate_path_error(error);
}

#[tokio::test(flavor = "current_thread")]
async fn byte_modified_payload_fails_before_handler_even_when_json_is_equivalent() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Stripe,
        "/webhooks/stripe",
        "stripe",
    )]);
    let now = unix_now();
    let signed_body = br#"{"id":"evt_tamper","type":"invoice.paid"}"#;
    let modified_body = br#"{"id": "evt_tamper", "type": "invoice.paid"}"#;

    let response = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature(CURRENT_SECRET, now, signed_body),
        )
        .body(modified_body.as_slice())
        .send()
        .await;

    let json = problem_json(&response, 401);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("signature"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn rejects_missing_malformed_stale_and_bad_signatures_with_problem_details() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Stripe,
        "/webhooks/stripe",
        "stripe",
    )]);
    let body = br#"{"id":"evt_bad","type":"invoice.paid"}"#;
    let now = unix_now();

    let missing = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&missing, 400);

    let malformed = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header("stripe-signature", "not-a-stripe-signature")
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&malformed, 400);

    // Use a 600s offset — well beyond the 300s tolerance — so that the few
    // seconds of test execution time on a slow Windows CI runner never shrinks
    // the skew below the threshold and causes a spurious 200.
    let stale_timestamp = now - 600;
    let stale = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature(CURRENT_SECRET, stale_timestamp, body),
        )
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&stale, 401);

    // Capture the future timestamp immediately before sending so that only the
    // round-trip time (not prior requests) affects the skew.
    let future_timestamp = unix_now() + 600;
    let future = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature(CURRENT_SECRET, future_timestamp, body),
        )
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&future, 401);

    let bad = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature("wrong-webhook-secret-32-bytes!!", now, body),
        )
        .body(body.as_slice())
        .send()
        .await;
    problem_json(&bad, 401);

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn duplicate_delivery_ids_are_rejected_deterministically() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    let body = br#"{"action":"opened"}"#;
    let signature = github_signature(CURRENT_SECRET, body);

    let first = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "same-delivery")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    first.assert_ok();

    let second = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "same-delivery")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    let json = problem_json(&second, 409);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("duplicate"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn custom_replay_store_failures_are_reported_as_service_unavailable() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let config = autumn_web::webhook::WebhookConfig {
        endpoints: vec![endpoint(
            WebhookProvider::Github,
            "/webhooks/github",
            "github",
        )],
        ..Default::default()
    };
    let registry = WebhookRegistry::from_config_with_replay_store(&config, UnavailableReplayStore)
        .expect("custom replay store should be installable");
    let client = client_with_registry(registry);
    let body = br#"{"action":"opened"}"#;

    let response = client
        .post("/webhooks/github")
        .header(
            "x-hub-signature-256",
            &github_signature(CURRENT_SECRET, body),
        )
        .header("x-github-delivery", "store-outage-delivery")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;

    response.assert_status(503);
    let json: serde_json::Value = response.json();
    assert_eq!(json["status"], 503);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("custom replay backend offline"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 0);
}

#[tokio::test(flavor = "current_thread")]
async fn in_memory_replay_store_rejects_duplicates_until_window_expires() {
    let store = InMemoryWebhookReplayStore::default();
    let received_at = UNIX_EPOCH + Duration::from_secs(1_000);
    let window = Duration::from_secs(300);

    assert!(
        store
            .check_and_insert("stripe:stripe:evt_replay", received_at, window)
            .await
            .expect("in-memory replay store should not fail")
    );
    assert!(
        !store
            .check_and_insert(
                "stripe:stripe:evt_replay",
                received_at + Duration::from_secs(299),
                window,
            )
            .await
            .expect("in-memory replay store should not fail")
    );
    assert!(
        store
            .check_and_insert(
                "stripe:stripe:evt_replay",
                received_at + Duration::from_secs(301),
                window,
            )
            .await
            .expect("in-memory replay store should not fail")
    );
}

#[tokio::test(flavor = "current_thread")]
async fn previous_secret_is_accepted_during_rotation() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    let body = br#"{"action":"closed"}"#;

    let response = client
        .post("/webhooks/github")
        .header(
            "x-hub-signature-256",
            &github_signature(PREVIOUS_SECRET, body),
        )
        .header("x-github-delivery", "rotated-delivery")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;

    response.assert_ok();
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[test]
fn production_config_rejects_missing_or_weak_webhook_secret() {
    let mut missing = webhook_config(vec![WebhookEndpointConfig {
        name: "stripe".to_owned(),
        path: "/webhooks/stripe".to_owned(),
        provider: WebhookProvider::Stripe,
        secret: None,
        previous_secrets: Vec::new(),
        ..Default::default()
    }]);
    missing.profile = Some("prod".to_owned());
    let error = missing
        .validate()
        .expect_err("prod webhook secret must be required");
    assert!(
        error.to_string().contains("webhook")
            && error.to_string().contains("stripe")
            && error.to_string().contains("secret")
    );

    let mut weak = webhook_config(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    weak.profile = Some("prod".to_owned());
    weak.security.webhooks.endpoints[0].secret = Some("secret".to_owned());
    let error = weak
        .validate()
        .expect_err("weak prod webhook secret must fail");
    assert!(
        error.to_string().contains("webhook")
            && error.to_string().contains("github")
            && error.to_string().contains("template")
    );
}

#[test]
fn production_config_requires_shared_replay_backend_unless_explicitly_allowed() {
    let mut config = webhook_config(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    config.profile = Some("prod".to_owned());

    let error = config
        .validate()
        .expect_err("prod webhook replay protection must reject memory backend");
    assert!(
        error.to_string().contains("replay")
            && error.to_string().contains("memory")
            && error.to_string().contains("production")
    );

    config.security.webhooks.replay.allow_memory_in_production = true;
    config
        .validate()
        .expect("explicit memory replay opt-in should validate");
}

#[test]
fn webhook_replay_backend_loads_from_toml_and_env() {
    let config: AutumnConfig = toml::from_str(
        r#"
            [security.webhooks.replay]
            backend = "redis"
            allow_memory_in_production = false

            [security.webhooks.replay.redis]
            url = "redis://localhost:6379/3"
            key_prefix = "myapp:webhooks:replay"
        "#,
    )
    .expect("webhook replay config should parse");
    assert_eq!(
        config.security.webhooks.replay.backend,
        WebhookReplayBackend::Redis
    );
    assert_eq!(
        config.security.webhooks.replay.redis.url.as_deref(),
        Some("redis://localhost:6379/3")
    );
    assert_eq!(
        config.security.webhooks.replay.redis.key_prefix,
        "myapp:webhooks:replay"
    );

    let env = MockEnv::new()
        .with("AUTUMN_SECURITY__WEBHOOKS__REPLAY__BACKEND", "redis")
        .with(
            "AUTUMN_SECURITY__WEBHOOKS__REPLAY__REDIS__URL",
            "redis://redis:6379/5",
        )
        .with(
            "AUTUMN_SECURITY__WEBHOOKS__REPLAY__REDIS__KEY_PREFIX",
            "env:webhooks:replay",
        )
        .with(
            "AUTUMN_SECURITY__WEBHOOKS__REPLAY__ALLOW_MEMORY_IN_PRODUCTION",
            "true",
        );
    let mut config = AutumnConfig::default();
    config.apply_env_overrides_with_env(&env);
    assert_eq!(
        config.security.webhooks.replay.backend,
        WebhookReplayBackend::Redis
    );
    assert_eq!(
        config.security.webhooks.replay.redis.url.as_deref(),
        Some("redis://redis:6379/5")
    );
    assert_eq!(
        config.security.webhooks.replay.redis.key_prefix,
        "env:webhooks:replay"
    );
    assert!(config.security.webhooks.replay.allow_memory_in_production);
}

#[cfg(not(feature = "redis"))]
#[test]
fn redis_replay_backend_requires_redis_feature() {
    let mut config = webhook_config(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    config.security.webhooks.replay.backend = WebhookReplayBackend::Redis;
    config.security.webhooks.replay.redis.url = Some("redis://localhost:6379/0".to_owned());

    let error = config
        .validate()
        .expect_err("redis replay backend must require redis feature");
    assert!(
        error.to_string().contains("redis") && error.to_string().contains("feature"),
        "{error}"
    );
}

#[cfg(feature = "redis")]
#[test]
fn redis_replay_backend_requires_url() {
    let mut config = webhook_config(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    config.security.webhooks.replay.backend = WebhookReplayBackend::Redis;

    let error = config
        .validate()
        .expect_err("redis replay backend must require a url");
    assert!(
        error.to_string().contains("redis") && error.to_string().contains("url"),
        "{error}"
    );
}

#[test]
fn disabled_replay_endpoint_does_not_require_replay_backend_configuration() {
    let mut config = autumn_web::webhook::WebhookConfig {
        replay: autumn_web::webhook::WebhookReplayConfig {
            backend: WebhookReplayBackend::Redis,
            ..Default::default()
        },
        endpoints: vec![
            endpoint(WebhookProvider::Github, "/webhooks/github", "github")
                .without_replay_protection(),
        ],
    };

    config
        .validate(false)
        .expect("disabled replay should not validate the replay backend");
    WebhookRegistry::from_config(&config)
        .expect("disabled replay should not construct the unused replay backend");

    config.endpoints[0].replay_protection = true;
    let error = config
        .validate(false)
        .expect_err("enabled replay should validate the configured backend");
    assert!(
        error.to_string().contains("redis"),
        "unexpected validation error: {error}"
    );
}

#[test]
fn webhook_secret_can_be_sourced_from_environment() {
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(
        dir.path().join("autumn.toml"),
        r#"
            [security.webhooks]

            [[security.webhooks.endpoints]]
            name = "stripe"
            path = "/webhooks/stripe"
            provider = "stripe"
            secret_env = "STRIPE_WEBHOOK_SECRET"
            previous_secret_envs = ["STRIPE_WEBHOOK_SECRET_PREVIOUS"]
        "#,
    )
    .expect("write config");

    let env = MockEnv::new()
        .with("AUTUMN_ENV", "test")
        .with("AUTUMN_MANIFEST_DIR", dir.path().to_str().unwrap())
        .with("STRIPE_WEBHOOK_SECRET", CURRENT_SECRET)
        .with("STRIPE_WEBHOOK_SECRET_PREVIOUS", PREVIOUS_SECRET);

    let config = AutumnConfig::load_with_env(&env).expect("config should load");
    let endpoint = &config.security.webhooks.endpoints[0];
    assert_eq!(endpoint.secret.as_deref(), Some(CURRENT_SECRET));
    assert_eq!(endpoint.previous_secrets, vec![PREVIOUS_SECRET.to_owned()]);
}

#[tokio::test(flavor = "current_thread")]
async fn toml_provider_preset_applies_signature_header_defaults() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let dir = tempfile::tempdir().expect("temp dir");
    std::fs::write(
        dir.path().join("autumn.toml"),
        r#"
            [security.webhooks]

            [[security.webhooks.endpoints]]
            name = "stripe"
            path = "/webhooks/stripe"
            provider = "stripe"
            secret_env = "STRIPE_WEBHOOK_SECRET"
        "#,
    )
    .expect("write config");
    let env = MockEnv::new()
        .with("AUTUMN_ENV", "test")
        .with("AUTUMN_MANIFEST_DIR", dir.path().to_str().unwrap())
        .with("STRIPE_WEBHOOK_SECRET", CURRENT_SECRET);
    let config = AutumnConfig::load_with_env(&env).expect("config should load");
    let client = TestApp::new()
        .config(config)
        .routes(routes![stripe_webhook])
        .build();
    let now = unix_now();
    let body = br#"{"id":"evt_toml","type":"invoice.paid"}"#;

    let response = client
        .post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header(
            "stripe-signature",
            &stripe_signature(CURRENT_SECRET, now, body),
        )
        .body(body.as_slice())
        .send()
        .await;

    response.assert_ok();
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn replay_attack_with_modified_delivery_id_is_rejected() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    let body = br#"{"action":"opened"}"#;
    let signature = github_signature(CURRENT_SECRET, body);

    let first = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-1")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    first.assert_ok();

    // Replay the same body & signature, but with a different delivery ID.
    // This should still be rejected as a duplicate because the body (signature) has not changed.
    let second = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-2")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    let json = problem_json(&second, 409);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("duplicate"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn webhook_endpoints_exempt_from_csrf() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);

    let endpoints = vec![endpoint(
        WebhookProvider::Stripe,
        "/webhooks/stripe",
        "stripe",
    )];
    let mut config = webhook_config(endpoints);
    config.security.csrf.enabled = true;

    let client = TestApp::new()
        .config(config)
        .routes(routes![stripe_webhook])
        .build();

    let timestamp = unix_now();
    let body = br#"{"id":"evt_123"}"#;
    let signature = stripe_signature(CURRENT_SECRET, timestamp, body);

    client
        .post("/webhooks/stripe")
        .header("stripe-signature", &signature)
        .body(body.as_slice())
        .send()
        .await
        .assert_ok();

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[post("/webhooks/failing")]
async fn failing_webhook(_webhook: SignedWebhook) -> impl IntoResponse {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    StatusCode::INTERNAL_SERVER_ERROR
}

#[tokio::test]
async fn webhook_replay_key_released_on_failure() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);

    let endpoints = vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/failing",
        "failing",
    )];
    let client = TestApp::new()
        .config(webhook_config(endpoints))
        .routes(routes![failing_webhook])
        .build();

    let body = br#"{"action":"opened"}"#;
    let signature = github_signature(CURRENT_SECRET, body);

    // 1. Send first request. It should hit the handler and fail with 500.
    client
        .post("/webhooks/failing")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-fail")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await
        .assert_status(500);

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);

    // 2. Since it failed with 500, the replay key must be released.
    // Send the duplicate request. It should hit the handler again (returning 500)
    // instead of being rejected as a duplicate (which would return 409).
    client
        .post("/webhooks/failing")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-fail")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await
        .assert_status(500);

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 2);
}

#[post("/webhooks/panicking")]
async fn panicking_webhook(_webhook: SignedWebhook) -> impl IntoResponse {
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    assert!(
        !std::convert::identity(true),
        "intentional panic in webhook handler"
    );
    StatusCode::OK
}

#[tokio::test]
async fn webhook_replay_key_released_on_panic() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);

    let endpoints = vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/panicking",
        "panicking",
    )];
    let client = TestApp::new()
        .config(webhook_config(endpoints))
        .routes(routes![panicking_webhook])
        .build();

    let body = br#"{"action":"opened"}"#;
    let signature = github_signature(CURRENT_SECRET, body);

    // 1. Send first request. It should hit the handler and panic.
    // Axum/ReportingLayer will catch the panic and return 500.
    client
        .post("/webhooks/panicking")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-panic")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await
        .assert_status(500);

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);

    // Give background spawned cleanup task a chance to run
    tokio::task::yield_now().await;

    // 2. Since it panicked, the replay key must be released.
    // Send the duplicate request. It should hit the handler again (and panic/return 500)
    // instead of being rejected as a duplicate (which would return 409).
    client
        .post("/webhooks/panicking")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "delivery-panic")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await
        .assert_status(500);

    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "current_thread")]
async fn test_duplicate_id_replay_same_id_different_sig_rejected() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    let body1 = br#"{"action":"opened"}"#;
    let signature1 = github_signature(CURRENT_SECRET, body1);

    let first = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature1)
        .header("x-github-delivery", "same-id")
        .header("x-github-event", "pull_request")
        .body(body1.as_slice())
        .send()
        .await;
    first.assert_ok();

    let body2 = br#"{"action":"synchronize"}"#;
    let signature2 = github_signature(CURRENT_SECRET, body2);

    let second = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature2)
        .header("x-github-delivery", "same-id")
        .header("x-github-event", "pull_request")
        .body(body2.as_slice())
        .send()
        .await;
    let json = problem_json(&second, 409);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("duplicate"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}

#[tokio::test(flavor = "current_thread")]
async fn test_modified_id_replay_different_id_same_sig_rejected() {
    let _guard = TEST_LOCK.lock().await;
    HANDLER_CALLS.store(0, Ordering::SeqCst);
    let client = client(vec![endpoint(
        WebhookProvider::Github,
        "/webhooks/github",
        "github",
    )]);
    let body = br#"{"action":"opened"}"#;
    let signature = github_signature(CURRENT_SECRET, body);

    let first = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "id-1")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    first.assert_ok();

    let second = client
        .post("/webhooks/github")
        .header("x-hub-signature-256", &signature)
        .header("x-github-delivery", "id-2")
        .header("x-github-event", "pull_request")
        .body(body.as_slice())
        .send()
        .await;
    let json = problem_json(&second, 409);
    assert!(
        json["detail"]
            .as_str()
            .is_some_and(|detail| detail.contains("duplicate"))
    );
    assert_eq!(HANDLER_CALLS.load(Ordering::SeqCst), 1);
}