autumn-web 0.4.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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! Security configuration for Autumn applications.
//!
//! Controls security headers and CSRF protection. All settings have
//! sensible defaults and are profile-aware:
//!
//! - **`dev`**: Relaxed -- CSRF disabled, HSTS off, permissive headers.
//! - **`prod`**: Strict -- CSRF enabled, HSTS on, all protective headers active.
//!
//! Session and authentication configuration live in their own modules
//! ([`crate::session::SessionConfig`], [`crate::auth::AuthConfig`]).
//!
//! # `autumn.toml` example
//!
//! ```toml
//! [security.headers]
//! x_frame_options = "DENY"
//! content_security_policy = "default-src 'self'"
//!
//! [security.csrf]
//! enabled = true
//!
//! [security.rate_limit]
//! enabled = true
//! requests_per_second = 10.0
//! burst = 20
//! ```
//!
//! # Environment variable reference
//!
//! | Variable | Config field | Type |
//! |----------|-------------|------|
//! | `AUTUMN_SECURITY__HEADERS__X_FRAME_OPTIONS` | `security.headers.x_frame_options` | `String` |
//! | `AUTUMN_SECURITY__HEADERS__HSTS_MAX_AGE_SECS` | `security.headers.hsts_max_age_secs` | `u64` |
//! | `AUTUMN_SECURITY__HEADERS__CONTENT_SECURITY_POLICY` | `security.headers.content_security_policy` | `String` |
//! | `AUTUMN_SECURITY__CSRF__ENABLED` | `security.csrf.enabled` | `bool` |
//! | `AUTUMN_SECURITY__RATE_LIMIT__ENABLED` | `security.rate_limit.enabled` | `bool` |
//! | `AUTUMN_SECURITY__RATE_LIMIT__REQUESTS_PER_SECOND` | `security.rate_limit.requests_per_second` | `f64` |
//! | `AUTUMN_SECURITY__RATE_LIMIT__BURST` | `security.rate_limit.burst` | `u32` |
//! | `AUTUMN_SECURITY__RATE_LIMIT__TRUST_FORWARDED_HEADERS` | `security.rate_limit.trust_forwarded_headers` | `bool` |
//! | `AUTUMN_SECURITY__RATE_LIMIT__TRUSTED_PROXIES` | `security.rate_limit.trusted_proxies` | comma-separated `String` |
//! | `AUTUMN_SECURITY__UPLOAD__MAX_REQUEST_SIZE_BYTES` | `security.upload.max_request_size_bytes` | `usize` |
//! | `AUTUMN_SECURITY__UPLOAD__MAX_FILE_SIZE_BYTES` | `security.upload.max_file_size_bytes` | `usize` |
//! | `AUTUMN_SECURITY__UPLOAD__ALLOWED_MIME_TYPES` | `security.upload.allowed_mime_types` | comma-separated `String` |
//! | `AUTUMN_SECURITY__WEBHOOKS__REPLAY__BACKEND` | `security.webhooks.replay.backend` | `memory` / `redis` |
//! | `AUTUMN_SECURITY__WEBHOOKS__REPLAY__REDIS__URL` | `security.webhooks.replay.redis.url` | `String` |
//! | `AUTUMN_SECURITY__WEBHOOKS__REPLAY__REDIS__KEY_PREFIX` | `security.webhooks.replay.redis.key_prefix` | `String` |
//! | `AUTUMN_SECURITY__WEBHOOKS__REPLAY__ALLOW_MEMORY_IN_PRODUCTION` | `security.webhooks.replay.allow_memory_in_production` | `bool` |
//! | per-endpoint `secret_env` | `security.webhooks.endpoints[*].secret` | environment variable name |
//!
//! Setting any header value to an empty string disables it (the header is
//! not emitted). This is the escape hatch for opting out of a default.

use std::sync::Arc;

use serde::Deserialize;

// ── Signing secret contract ────────────────────────────────────────────────

/// Minimum byte length for a valid production signing secret (32 bytes / 256 bits).
///
/// A hex-encoded 32-byte value is 64 characters. Anything shorter is rejected
/// at production startup.
pub const MIN_SECRET_LEN: usize = 32;

/// Known demo / template / placeholder values that must never reach production.
const DEMO_VALUES: &[&str] = &[
    "changeme",
    "change_me",
    "change-me",
    "secret",
    "supersecret",
    "super-secret",
    "super_secret",
    "your-secret-here",
    "your_secret_here",
    "insert-secret-here",
    "replace-this",
    "replace_me",
    "todo",
    "fixme",
    "example",
    "placeholder",
    "dev_only",
    "dev-only",
    "test_secret",
    "test-secret",
    "test",
    "password",
];

/// Signing-secret configuration for HMAC-signed framework surfaces.
///
/// The signing secret is the shared key used to sign sessions, CSRF tokens,
/// flash/signed-cookie state, and local-storage signed URLs.
///
/// # Development and test
///
/// Leave `secret` unset. An ephemeral per-process key is generated automatically.
/// This means sessions and signed URLs do **not** survive process restarts and
/// replicas cannot share state — acceptable in dev, unacceptable in production.
///
/// # Production
///
/// Set `secret` via the `AUTUMN_SECURITY__SIGNING_SECRET` environment variable
/// (or `[security.signing_secret] secret` in `autumn.toml`). The secret must be:
/// - At least [`MIN_SECRET_LEN`] bytes long.
/// - Not a known template/demo value.
/// - Stable across restarts and identical on every replica.
///
/// Generate a secret: `openssl rand -hex 32`
///
/// # Rotation
///
/// When rotating, move the current secret to `previous_secrets` and set the
/// new value in `secret`. New signatures use `secret`; tokens signed with any
/// entry in `previous_secrets` continue to validate during the grace window.
/// Remove expired entries from `previous_secrets` after the maximum relevant
/// cookie/token lifetime has elapsed.
///
/// # `autumn.toml` example
///
/// ```toml
/// [security.signing_secret]
/// # secret set via AUTUMN_SECURITY__SIGNING_SECRET env var (never commit this)
///
/// # rotation grace window — leave populated until all existing tokens expire:
/// previous_secrets = ["oldsecretvalue..."]
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SigningSecretConfig {
    /// The current signing secret. In production, must come from an environment
    /// variable or external secrets manager — never a committed literal.
    pub secret: Option<String>,

    /// Previous signing secrets accepted during a rotation grace window.
    ///
    /// New signatures always use `secret`. Tokens signed with an entry here
    /// remain valid until removed. Remove entries after the maximum relevant
    /// cookie/token lifetime has elapsed (e.g. `session.max_age_secs`).
    #[serde(default)]
    pub previous_secrets: Vec<String>,
}

/// Error returned when a signing secret fails production validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SigningSecretError {
    /// No secret is configured but the production profile requires one.
    MissingInProduction,
    /// The secret is too short to meet the minimum entropy requirement.
    TooShort {
        /// Actual byte length of the supplied secret.
        actual: usize,
        /// Minimum required byte length ([`MIN_SECRET_LEN`]).
        required: usize,
    },
    /// The secret matches a known insecure demo or template value.
    KnownWeakValue(String),
}

impl std::fmt::Display for SigningSecretError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingInProduction => write!(
                f,
                "signing secret is required in production; set \
                 AUTUMN_SECURITY__SIGNING_SECRET (generate with `openssl rand -hex 32`)"
            ),
            Self::TooShort { actual, required } => write!(
                f,
                "signing secret is too short ({actual} bytes, minimum {required}); \
                 generate one with `openssl rand -hex 32`"
            ),
            Self::KnownWeakValue(v) => write!(
                f,
                "signing secret looks like a template/demo value ({v:?}); \
                 generate one with `openssl rand -hex 32`"
            ),
        }
    }
}

/// Validate a signing secret for production use.
///
/// In development and test the check is skipped — any value (including `None`)
/// is accepted so zero-config local development continues to work.
///
/// In production:
/// - `None` → [`SigningSecretError::MissingInProduction`]
/// - Shorter than [`MIN_SECRET_LEN`] bytes → [`SigningSecretError::TooShort`]
/// - Matches a known demo/template string → [`SigningSecretError::KnownWeakValue`]
///
/// # Errors
///
/// Returns [`SigningSecretError`] when production validation fails.
pub fn validate_signing_secret(
    secret: Option<&str>,
    is_production: bool,
) -> Result<(), SigningSecretError> {
    if !is_production {
        return Ok(());
    }
    let secret = secret.ok_or(SigningSecretError::MissingInProduction)?;
    // Demo-value check first: "changeme" is more informative than "too short".
    let lower = secret.to_ascii_lowercase();
    for &demo in DEMO_VALUES {
        if lower == demo {
            return Err(SigningSecretError::KnownWeakValue(secret.to_owned()));
        }
    }
    let byte_len = secret.len();
    if byte_len < MIN_SECRET_LEN {
        return Err(SigningSecretError::TooShort {
            actual: byte_len,
            required: MIN_SECRET_LEN,
        });
    }
    Ok(())
}

// ── Resolved signing key material ─────────────────────────────────────────

/// HMAC-SHA256 of `message` under `key`, returned as lowercase hex.
///
/// # Panics
///
/// This should not panic because HMAC accepts keys of any length. A panic would
/// indicate a broken crypto crate invariant.
#[must_use]
pub fn hmac_sha256_hex(key: &[u8], message: &[u8]) -> String {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC accepts any key length");
    mac.update(message);
    let bytes = mac.finalize().into_bytes();
    bytes.iter().fold(String::with_capacity(64), |mut acc, b| {
        use std::fmt::Write as _;
        let _ = write!(acc, "{b:02x}");
        acc
    })
}

/// Constant-time string comparison for HMAC verification.
fn ct_eq_str(a: &str, b: &str) -> bool {
    use subtle::ConstantTimeEq;
    a.as_bytes().ct_eq(b.as_bytes()).into()
}

/// Generate a random 32-byte ephemeral key from two UUID v4 values.
fn generate_ephemeral_key() -> Vec<u8> {
    let a = uuid::Uuid::new_v4();
    let b = uuid::Uuid::new_v4();
    let mut bytes = vec![0u8; 32];
    bytes[..16].copy_from_slice(a.as_bytes());
    bytes[16..].copy_from_slice(b.as_bytes());
    bytes
}

/// Resolved signing keys for a running Autumn instance.
///
/// Created once at startup from [`SigningSecretConfig`] via [`resolve_signing_keys`]
/// and shared via `Arc` across session, CSRF, and local storage signing.
///
/// - `current` signs new tokens.
/// - `previous` are accepted during a rotation grace window.
#[derive(Clone, Debug)]
pub struct ResolvedSigningKeys {
    /// Key used to sign new tokens.
    pub current: Arc<[u8]>,
    /// Former keys accepted during a rotation grace window. New signatures always
    /// use `current`; tokens carrying a `previous` HMAC continue to verify until
    /// removed (see docs/guide/signing-secrets.md).
    pub previous: Vec<Arc<[u8]>>,
}

impl ResolvedSigningKeys {
    /// Build from raw byte vectors.
    pub fn new(current: Vec<u8>, previous: Vec<Vec<u8>>) -> Self {
        Self {
            current: current.into(),
            previous: previous.into_iter().map(|v: Vec<u8>| v.into()).collect(),
        }
    }

    /// HMAC-SHA256 of `message` under the current key, hex-encoded.
    pub fn sign(&self, message: &[u8]) -> String {
        hmac_sha256_hex(&self.current, message)
    }

    /// Returns `true` when `hex_sig` is a valid HMAC-SHA256 of `message` under
    /// any key (current first, then previous). All comparisons are constant-time.
    pub fn verify(&self, message: &[u8], hex_sig: &str) -> bool {
        if ct_eq_str(&hmac_sha256_hex(&self.current, message), hex_sig) {
            return true;
        }
        for prev in &self.previous {
            if ct_eq_str(&hmac_sha256_hex(prev, message), hex_sig) {
                return true;
            }
        }
        false
    }
}

/// Resolve signing keys from a [`SigningSecretConfig`].
///
/// - When `secret` is set, its bytes become the current key.
/// - When `secret` is absent (dev/test), an ephemeral random key is generated.
///   This means signed tokens do not survive process restarts.
/// - `previous_secrets` are always included for rotation grace-window verification.
///
/// Production boot validation (requiring `secret` to be non-empty, long enough,
/// and not a demo value) is a separate step via [`validate_signing_secret`].
pub fn resolve_signing_keys(config: &SigningSecretConfig) -> ResolvedSigningKeys {
    let current = config
        .secret
        .as_deref()
        .map_or_else(generate_ephemeral_key, |s| s.as_bytes().to_vec());
    let previous = config
        .previous_secrets
        .iter()
        .map(|s| s.as_bytes().to_vec())
        .collect();
    ResolvedSigningKeys::new(current, previous)
}

/// Top-level security configuration section.
///
/// Groups security headers and CSRF protection under `[security]`
/// in `autumn.toml`.
///
/// # Examples
///
/// ```rust
/// use autumn_web::security::SecurityConfig;
///
/// let config = SecurityConfig::default();
/// assert_eq!(config.headers.x_frame_options, "DENY");
/// assert!(config.headers.x_content_type_options);
/// assert!(!config.csrf.enabled);
/// assert!(!config.rate_limit.enabled);
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SecurityConfig {
    /// HTTP security headers applied to all responses.
    #[serde(default)]
    pub headers: HeadersConfig,

    /// CSRF (Cross-Site Request Forgery) protection.
    #[serde(default)]
    pub csrf: CsrfConfig,

    /// Rate limiting (per-client-IP token bucket).
    #[serde(default)]
    pub rate_limit: RateLimitConfig,

    /// Multipart upload safeguards and validation policy.
    #[serde(default)]
    pub upload: UploadConfig,

    /// Signed webhook intake endpoints.
    #[serde(default)]
    pub webhooks: crate::webhook::WebhookConfig,

    /// HTTP status returned when a [`Policy`](crate::authorization::Policy)
    /// denies a record-level action. Defaults to `"404"` to mirror the
    /// Rails / Phoenix posture of hiding existence from unauthorized
    /// clients.
    #[serde(default)]
    pub forbidden_response: crate::authorization::ForbiddenResponse,

    /// Allow `#[repository(api = "...")]` to mount auto-generated
    /// CRUD endpoints in `prod` builds without a paired `policy =`
    /// argument.
    ///
    /// Default: `false`. The framework refuses to start when an
    /// `api =` repository has no `policy =` because the auto-
    /// generated endpoints would be reachable by any authenticated
    /// user. Flip this to `true` only when the lack of authz is
    /// genuinely intended (e.g. a fully-public read-only API).
    #[serde(default)]
    pub allow_unauthorized_repository_api: bool,

    /// Signing-secret configuration for HMAC-signed framework surfaces.
    ///
    /// Covers sessions, CSRF tokens, flash/signed-cookie state, and
    /// local-storage signed URLs. In dev the framework generates an
    /// ephemeral per-process key; production MUST set a stable, private
    /// secret via `AUTUMN_SECURITY__SIGNING_SECRET`.
    #[serde(default)]
    pub signing_secret: SigningSecretConfig,
}

/// Security response headers configuration.
///
/// Controls which protective HTTP headers are added to every response.
/// Follows OWASP security header recommendations.
///
/// # Defaults
///
/// | Field | Default |
/// |-------|---------|
/// | `x_frame_options` | `"DENY"` |
/// | `x_content_type_options` | `true` |
/// | `xss_protection` | `true` |
/// | `strict_transport_security` | `false` |
/// | `hsts_max_age_secs` | `31_536_000` (1 year) |
/// | `hsts_include_subdomains` | `true` |
/// | `content_security_policy` | htmx-compatible policy (see [`default_content_security_policy`]) |
/// | `referrer_policy` | `"strict-origin-when-cross-origin"` |
/// | `permissions_policy` | `""` (disabled) |
///
/// # Examples
///
/// ```toml
/// [security.headers]
/// x_frame_options = "SAMEORIGIN"
/// content_security_policy = "default-src 'self'; script-src 'self'"
/// strict_transport_security = true
/// ```
#[derive(Debug, Clone, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct HeadersConfig {
    /// `X-Frame-Options` header value. Default: `"DENY"`.
    ///
    /// Prevents the page from being loaded in an iframe. Common values:
    /// - `"DENY"` -- never allow framing
    /// - `"SAMEORIGIN"` -- allow framing by same origin
    /// - `""` -- do not send the header
    #[serde(default = "default_x_frame_options")]
    pub x_frame_options: String,

    /// Add `X-Content-Type-Options: nosniff`. Default: `true`.
    ///
    /// Prevents MIME-type sniffing attacks.
    #[serde(default = "default_true")]
    pub x_content_type_options: bool,

    /// Add `X-XSS-Protection: 1; mode=block`. Default: `true`.
    ///
    /// Enables the browser's built-in XSS filter (legacy but still useful).
    #[serde(default = "default_true")]
    pub xss_protection: bool,

    /// Add `Strict-Transport-Security` (HSTS) header. Default: `false`.
    ///
    /// When `true`, tells browsers to only connect via HTTPS. Enabled
    /// automatically for `prod` profile via smart defaults.
    #[serde(default)]
    pub strict_transport_security: bool,

    /// HSTS `max-age` in seconds. Default: `31_536_000` (1 year).
    ///
    /// Only used when `strict_transport_security` is `true`.
    #[serde(default = "default_hsts_max_age")]
    pub hsts_max_age_secs: u64,

    /// Include subdomains in HSTS policy. Default: `true`.
    #[serde(default = "default_true")]
    pub hsts_include_subdomains: bool,

    /// `Content-Security-Policy` header value.
    ///
    /// Defaults to an htmx-compatible, same-origin policy (see
    /// [`default_content_security_policy`]). When set to an empty string,
    /// the header is not emitted (explicit opt-out).
    ///
    /// The default allows htmx to function normally because htmx and Autumn's
    /// htmx CSRF helper are served from the same origin and operate via
    /// `addEventListener` rather than inline scripts.
    #[serde(default = "default_content_security_policy")]
    pub content_security_policy: String,

    /// `Referrer-Policy` header value. Default: `"strict-origin-when-cross-origin"`.
    #[serde(default = "default_referrer_policy")]
    pub referrer_policy: String,

    /// `Permissions-Policy` header value. Default: `""` (not sent).
    ///
    /// Controls which browser features and APIs can be used.
    /// Example: `"camera=(), microphone=(), geolocation=()"`.
    #[serde(default)]
    pub permissions_policy: String,
}

impl Default for HeadersConfig {
    fn default() -> Self {
        Self {
            x_frame_options: default_x_frame_options(),
            x_content_type_options: true,
            xss_protection: true,
            strict_transport_security: false,
            hsts_max_age_secs: default_hsts_max_age(),
            hsts_include_subdomains: true,
            content_security_policy: default_content_security_policy(),
            referrer_policy: default_referrer_policy(),
            permissions_policy: String::new(),
        }
    }
}

/// CSRF (Cross-Site Request Forgery) protection configuration.
///
/// When enabled, mutating requests (POST, PUT, DELETE, PATCH) must include
/// a valid CSRF token either as:
///
/// - An HTTP header (default: `X-CSRF-Token`)
/// - A form field (default: `_csrf`)
///
/// The token is generated per-session and stored in a cookie.
///
/// # Defaults
///
/// | Field | Default |
/// |-------|---------|
/// | `enabled` | `false` |
/// | `token_header` | `"X-CSRF-Token"` |
/// | `form_field` | `"_csrf"` |
/// | `cookie_name` | `"autumn-csrf"` |
/// | `safe_methods` | `["GET", "HEAD", "OPTIONS", "TRACE"]` |
/// | `exempt_paths` | `[]` |
///
/// # Examples
///
/// ```toml
/// [security.csrf]
/// enabled = true
/// token_header = "X-XSRF-Token"
/// cookie_name = "XSRF-TOKEN"
/// exempt_paths = ["/api/"]
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct CsrfConfig {
    /// Enable CSRF protection. Default: `false`.
    ///
    /// Enabled automatically for `prod` profile via smart defaults.
    #[serde(default)]
    pub enabled: bool,

    /// HTTP header name for the CSRF token. Default: `"X-CSRF-Token"`.
    #[serde(default = "default_csrf_header")]
    pub token_header: String,

    /// Form field name for the CSRF token. Default: `"_csrf"`.
    #[serde(default = "default_csrf_field")]
    pub form_field: String,

    /// Cookie name for storing the CSRF token. Default: `"autumn-csrf"`.
    #[serde(default = "default_csrf_cookie")]
    pub cookie_name: String,

    /// HTTP methods that do NOT require CSRF validation.
    /// Default: `["GET", "HEAD", "OPTIONS", "TRACE"]`.
    #[serde(default = "default_safe_methods")]
    pub safe_methods: Vec<String>,

    /// Request path prefixes that are exempt from CSRF validation.
    /// Default: `[]`.
    ///
    /// Use this to opt JSON API routes out of CSRF when they authenticate
    /// with bearer tokens or other non-cookie credentials. Matches are by
    /// prefix on the request path, e.g. `"/api/"` exempts all routes
    /// under `/api/`.
    #[serde(default)]
    pub exempt_paths: Vec<String>,
}

impl Default for CsrfConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            token_header: default_csrf_header(),
            form_field: default_csrf_field(),
            cookie_name: default_csrf_cookie(),
            safe_methods: default_safe_methods(),
            exempt_paths: Vec::new(),
        }
    }
}

/// Rate limiting configuration.
///
/// Applies a per-client-IP token bucket to every request. When a client
/// exceeds their bucket, the middleware returns `429 Too Many Requests`
/// with a `Retry-After` header indicating when to retry.
///
/// # Defaults
///
/// | Field | Default |
/// |-------|---------|
/// | `enabled` | `false` |
/// | `requests_per_second` | `10.0` |
/// | `burst` | `20` |
/// | `trust_forwarded_headers` | `false` |
/// | `trusted_proxies` | `[]` |
///
/// # Client IP resolution
///
/// By default the limiter keys on the **connection peer address**. This
/// prevents clients from bypassing throttling by rotating `X-Forwarded-For`
/// values. Set `trust_forwarded_headers = true` only when the server
/// sits behind a trusted reverse proxy that strips and rewrites
/// forwarding headers on every request.
///
/// If trusted upstream proxies append to `X-Forwarded-For`, configure
/// `trusted_proxies` with the trusted proxy IPs or CIDR ranges. Autumn
/// then walks the header from right to left, skips those trusted proxy
/// hops, and keys the bucket on the nearest untrusted client IP.
///
/// # Examples
///
/// ```toml
/// [security.rate_limit]
/// enabled = true
/// requests_per_second = 5.0
/// burst = 10
/// trust_forwarded_headers = false
/// trusted_proxies = ["10.0.0.10", "203.0.113.0/24"]
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct RateLimitConfig {
    /// Enable rate limiting. Default: `false`.
    #[serde(default)]
    pub enabled: bool,

    /// Steady-state refill rate in requests per second. Default: `10.0`.
    #[serde(default = "default_rps")]
    pub requests_per_second: f64,

    /// Maximum burst capacity (number of tokens the bucket can hold).
    /// Default: `20`.
    #[serde(default = "default_burst")]
    pub burst: u32,

    /// Consult `X-Forwarded-For` / `X-Real-IP` before the connection peer
    /// when identifying the client. Default: `false`.
    ///
    /// Enable ONLY when the server is behind a trusted reverse proxy that
    /// fully overrides these headers on every request. Otherwise a client
    /// can rotate header values to bypass throttling.
    #[serde(default)]
    pub trust_forwarded_headers: bool,

    /// Trusted proxy IP addresses or CIDR ranges to skip at the right
    /// side of an appended `X-Forwarded-For` chain.
    ///
    /// This is only used when `trust_forwarded_headers = true`. Include
    /// the immediate peer proxy when `ConnectInfo` is available; forwarded
    /// headers from non-trusted peers, or requests without peer metadata,
    /// are ignored. Invalid entries are ignored; if every configured
    /// entry is invalid, forwarded headers are ignored rather than trusted.
    #[serde(default)]
    pub trusted_proxies: Vec<String>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            requests_per_second: default_rps(),
            burst: default_burst(),
            trust_forwarded_headers: false,
            trusted_proxies: Vec::new(),
        }
    }
}

/// Multipart upload configuration.
///
/// Applies framework-level guardrails for `multipart/form-data` requests:
///
/// - `max_request_size_bytes`: global request body cap (enforced by middleware)
/// - `max_file_size_bytes`: per-file cap for `crate::extract::Multipart` helpers
/// - `allowed_mime_types`: optional MIME-type allow list for uploaded parts
///
/// Leave `allowed_mime_types` empty to allow any content type.
#[derive(Debug, Clone, Deserialize)]
pub struct UploadConfig {
    /// Maximum total multipart request body size in bytes.
    #[serde(default = "default_max_request_size_bytes")]
    pub max_request_size_bytes: usize,
    /// Maximum individual uploaded file size in bytes.
    #[serde(default = "default_max_file_size_bytes")]
    pub max_file_size_bytes: usize,
    /// Optional allowed MIME types (e.g. `["image/png", "image/jpeg"]`).
    #[serde(default)]
    pub allowed_mime_types: Vec<String>,
}

impl Default for UploadConfig {
    fn default() -> Self {
        Self {
            max_request_size_bytes: default_max_request_size_bytes(),
            max_file_size_bytes: default_max_file_size_bytes(),
            allowed_mime_types: Vec::new(),
        }
    }
}

// ── Default value functions ────────────────────────────────────────

const fn default_true() -> bool {
    true
}

fn default_x_frame_options() -> String {
    "DENY".to_owned()
}

const fn default_hsts_max_age() -> u64 {
    31_536_000 // 1 year
}

fn default_referrer_policy() -> String {
    "strict-origin-when-cross-origin".to_owned()
}

/// Default `Content-Security-Policy` value.
///
/// Designed to be "sensible by default" while allowing htmx to function
/// normally when served from the same origin (as Autumn does for htmx and its
/// CSRF helper under `/static/js/`).
///
/// Directives:
/// - `default-src 'self'` -- everything defaults to same-origin
/// - `img-src 'self' data:` -- images from self and inline data URIs
/// - `style-src 'self' 'unsafe-inline'` -- same-origin stylesheets plus
///   inline `style` attributes (required by many UI libraries and
///   template engines)
/// - `script-src 'self'` -- only same-origin scripts; htmx and Autumn's htmx
///   CSRF helper work here because they are served from `/static/js/`
/// - `connect-src 'self'` -- `fetch`/`XHR`/htmx requests go to same origin
/// - `form-action 'self'` -- forms can only POST to same origin
/// - `frame-ancestors 'none'` -- matches the default `X-Frame-Options: DENY`
/// - `base-uri 'self'` -- prevents `<base>` hijacking
#[must_use]
pub fn default_content_security_policy() -> String {
    "default-src 'self'; \
     img-src 'self' data:; \
     style-src 'self' 'unsafe-inline'; \
     script-src 'self'; \
     connect-src 'self'; \
     form-action 'self'; \
     frame-ancestors 'none'; \
     base-uri 'self'"
        .to_owned()
}

fn default_csrf_header() -> String {
    "X-CSRF-Token".to_owned()
}

fn default_csrf_field() -> String {
    "_csrf".to_owned()
}

fn default_csrf_cookie() -> String {
    "autumn-csrf".to_owned()
}

fn default_safe_methods() -> Vec<String> {
    vec![
        "GET".to_owned(),
        "HEAD".to_owned(),
        "OPTIONS".to_owned(),
        "TRACE".to_owned(),
    ]
}

const fn default_rps() -> f64 {
    10.0
}

const fn default_burst() -> u32 {
    20
}

const fn default_max_request_size_bytes() -> usize {
    32 * 1024 * 1024
}

const fn default_max_file_size_bytes() -> usize {
    16 * 1024 * 1024
}

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

    // ── validate_signing_secret (RED phase) ─────────────────────────────────

    #[test]
    fn signing_secret_dev_skips_validation_with_none() {
        assert!(validate_signing_secret(None, false).is_ok());
    }

    #[test]
    fn signing_secret_dev_skips_validation_with_weak_value() {
        assert!(validate_signing_secret(Some("changeme"), false).is_ok());
    }

    #[test]
    fn signing_secret_dev_skips_validation_with_short_value() {
        assert!(validate_signing_secret(Some("short"), false).is_ok());
    }

    #[test]
    fn signing_secret_prod_missing_is_error() {
        let err = validate_signing_secret(None, true).unwrap_err();
        assert!(matches!(err, SigningSecretError::MissingInProduction));
    }

    #[test]
    fn signing_secret_prod_too_short_is_error() {
        let short = "a".repeat(MIN_SECRET_LEN - 1);
        let err = validate_signing_secret(Some(&short), true).unwrap_err();
        assert!(matches!(err, SigningSecretError::TooShort { .. }));
    }

    #[test]
    fn signing_secret_prod_exact_min_length_passes() {
        let exactly_min = "a".repeat(MIN_SECRET_LEN);
        assert!(validate_signing_secret(Some(&exactly_min), true).is_ok());
    }

    #[test]
    fn signing_secret_prod_known_demo_value_is_error() {
        let err = validate_signing_secret(Some("changeme"), true).unwrap_err();
        assert!(matches!(err, SigningSecretError::KnownWeakValue(_)));
    }

    #[test]
    fn signing_secret_prod_demo_value_case_insensitive() {
        let err = validate_signing_secret(Some("CHANGEME"), true).unwrap_err();
        assert!(matches!(err, SigningSecretError::KnownWeakValue(_)));
    }

    #[test]
    fn signing_secret_prod_valid_64char_hex_passes() {
        let secret = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
        assert!(validate_signing_secret(Some(secret), true).is_ok());
    }

    #[test]
    fn signing_secret_config_defaults_to_none() {
        let config = SigningSecretConfig::default();
        assert!(config.secret.is_none());
        assert!(config.previous_secrets.is_empty());
    }

    #[test]
    fn signing_secret_error_missing_display_mentions_env_var() {
        let err = SigningSecretError::MissingInProduction;
        assert!(err.to_string().contains("AUTUMN_SECURITY__SIGNING_SECRET"));
    }

    #[test]
    fn signing_secret_error_too_short_display_shows_lengths() {
        let err = SigningSecretError::TooShort {
            actual: 8,
            required: 32,
        };
        let s = err.to_string();
        assert!(s.contains('8'));
        assert!(s.contains("32"));
    }

    #[test]
    fn signing_secret_error_weak_value_display_mentions_demo() {
        let err = SigningSecretError::KnownWeakValue("changeme".to_owned());
        assert!(err.to_string().contains("template/demo"));
    }

    #[test]
    fn signing_secret_prod_too_short_error_reports_actual_length() {
        let short = "tooshort"; // 8 bytes
        let err = validate_signing_secret(Some(short), true).unwrap_err();
        if let SigningSecretError::TooShort { actual, required } = err {
            assert_eq!(actual, 8);
            assert_eq!(required, MIN_SECRET_LEN);
        } else {
            panic!("expected TooShort error");
        }
    }

    #[test]
    fn signing_secret_prod_secret_key_demo_value_fails() {
        assert!(matches!(
            validate_signing_secret(Some("secret"), true),
            Err(SigningSecretError::KnownWeakValue(_))
        ));
    }

    #[test]
    fn signing_secret_prod_supersecret_demo_value_fails() {
        assert!(matches!(
            validate_signing_secret(Some("supersecret"), true),
            Err(SigningSecretError::KnownWeakValue(_))
        ));
    }

    #[test]
    fn signing_secret_config_deserialize_from_toml() {
        let toml_str = r#"
            secret = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"
            previous_secrets = ["oldsecret01234567890123456789012"]
        "#;
        let config: SigningSecretConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            config.secret.as_deref(),
            Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4")
        );
        assert_eq!(config.previous_secrets.len(), 1);
    }

    #[test]
    fn security_config_defaults() {
        let config = SecurityConfig::default();
        assert_eq!(config.headers.x_frame_options, "DENY");
        assert!(config.headers.x_content_type_options);
        assert!(config.headers.xss_protection);
        assert!(!config.headers.strict_transport_security);
        assert_eq!(config.headers.hsts_max_age_secs, 31_536_000);
        // Default CSP is non-empty and htmx-compatible.
        assert!(!config.headers.content_security_policy.is_empty());
        assert!(
            config
                .headers
                .content_security_policy
                .contains("default-src 'self'")
        );
        assert!(
            config
                .headers
                .content_security_policy
                .contains("script-src 'self'")
        );
        assert_eq!(
            config.headers.referrer_policy,
            "strict-origin-when-cross-origin"
        );
    }

    #[test]
    fn default_csp_does_not_allow_unsafe_eval() {
        // htmx works without unsafe-eval; only `hx-on` opts into it.
        // Keep the default tight so that the baseline policy passes
        // Mozilla Observatory and similar automated scanners.
        let csp = default_content_security_policy();
        assert!(!csp.contains("'unsafe-eval'"), "csp = {csp}");
        assert!(
            !csp.contains("'unsafe-inline' 'unsafe-eval'"),
            "csp = {csp}"
        );
    }

    #[test]
    fn csp_can_be_disabled_via_toml_empty_string() {
        let toml_str = r#"
            content_security_policy = ""
        "#;
        let config: HeadersConfig = toml::from_str(toml_str).unwrap();
        assert!(config.content_security_policy.is_empty());
    }

    #[test]
    fn csp_can_be_overridden_via_toml() {
        let toml_str = r#"
            content_security_policy = "default-src 'none'"
        "#;
        let config: HeadersConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.content_security_policy, "default-src 'none'");
    }

    #[test]
    fn csrf_config_defaults() {
        let config = CsrfConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.token_header, "X-CSRF-Token");
        assert_eq!(config.form_field, "_csrf");
        assert_eq!(config.cookie_name, "autumn-csrf");
        assert_eq!(config.safe_methods.len(), 4);
    }

    #[test]
    fn headers_config_deserialize() {
        let toml_str = r#"
            x_frame_options = "SAMEORIGIN"
            strict_transport_security = true
            content_security_policy = "default-src 'self'"
        "#;
        let config: HeadersConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.x_frame_options, "SAMEORIGIN");
        assert!(config.strict_transport_security);
        assert_eq!(config.content_security_policy, "default-src 'self'");
        // Defaults for unspecified fields
        assert!(config.x_content_type_options);
        assert!(config.xss_protection);
    }

    #[test]
    fn csrf_config_deserialize() {
        let toml_str = r#"
            enabled = true
            token_header = "X-XSRF-Token"
        "#;
        let config: CsrfConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert_eq!(config.token_header, "X-XSRF-Token");
        assert_eq!(config.form_field, "_csrf"); // default preserved
    }

    #[test]
    fn rate_limit_config_defaults() {
        let config = RateLimitConfig::default();
        assert!(!config.enabled);
        assert!((config.requests_per_second - 10.0).abs() < f64::EPSILON);
        assert_eq!(config.burst, 20);
        assert!(!config.trust_forwarded_headers);
        assert!(config.trusted_proxies.is_empty());
    }

    #[test]
    fn rate_limit_config_deserialize() {
        let toml_str = r#"
            enabled = true
            requests_per_second = 5.0
            burst = 100
            trust_forwarded_headers = true
            trusted_proxies = ["10.0.0.10", "203.0.113.0/24"]
        "#;
        let config: RateLimitConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert!((config.requests_per_second - 5.0).abs() < f64::EPSILON);
        assert_eq!(config.burst, 100);
        assert!(config.trust_forwarded_headers);
        assert_eq!(config.trusted_proxies, vec!["10.0.0.10", "203.0.113.0/24"]);
    }

    #[test]
    fn rate_limit_config_partial_deserialize_uses_defaults() {
        let toml_str = "enabled = true";
        let config: RateLimitConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert!((config.requests_per_second - 10.0).abs() < f64::EPSILON);
        assert_eq!(config.burst, 20);
        assert!(!config.trust_forwarded_headers);
        assert!(config.trusted_proxies.is_empty());
    }

    #[test]
    fn upload_config_defaults() {
        let config = UploadConfig::default();
        assert_eq!(config.max_request_size_bytes, 32 * 1024 * 1024);
        assert_eq!(config.max_file_size_bytes, 16 * 1024 * 1024);
        assert!(config.allowed_mime_types.is_empty());
    }

    #[test]
    fn upload_config_deserialize() {
        let toml_str = r#"
            max_request_size_bytes = 1024
            max_file_size_bytes = 256
            allowed_mime_types = ["image/png", "image/jpeg"]
        "#;
        let config: UploadConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.max_request_size_bytes, 1024);
        assert_eq!(config.max_file_size_bytes, 256);
        assert_eq!(config.allowed_mime_types.len(), 2);
    }

    #[test]
    fn full_security_config_deserialize() {
        let toml_str = r#"
            [headers]
            x_frame_options = "DENY"
            strict_transport_security = true

            [csrf]
            enabled = true

            [rate_limit]
            enabled = true
            requests_per_second = 50.0
            burst = 100

            [upload]
            max_request_size_bytes = 4096
            max_file_size_bytes = 1024
            allowed_mime_types = ["text/plain"]
        "#;
        let config: SecurityConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.headers.x_frame_options, "DENY");
        assert!(config.headers.strict_transport_security);
        assert!(config.csrf.enabled);
        assert!(config.rate_limit.enabled);
        assert!((config.rate_limit.requests_per_second - 50.0).abs() < f64::EPSILON);
        assert_eq!(config.rate_limit.burst, 100);
        assert_eq!(config.upload.max_request_size_bytes, 4096);
        assert_eq!(config.upload.max_file_size_bytes, 1024);
        assert_eq!(config.upload.allowed_mime_types, vec!["text/plain"]);
    }

    // ── ResolvedSigningKeys + resolve_signing_keys (RED phase) ─────────────

    #[test]
    fn resolve_signing_keys_dev_generates_non_empty_ephemeral() {
        let config = SigningSecretConfig::default();
        let keys = resolve_signing_keys(&config);
        assert!(keys.current.len() >= MIN_SECRET_LEN);
    }

    #[test]
    fn resolve_signing_keys_prod_uses_secret_bytes() {
        let secret = "a".repeat(MIN_SECRET_LEN);
        let config = SigningSecretConfig {
            secret: Some(secret.clone()),
            previous_secrets: vec![],
        };
        let keys = resolve_signing_keys(&config);
        assert_eq!(keys.current.as_ref(), secret.as_bytes());
    }

    #[test]
    fn resolve_signing_keys_includes_previous_secrets() {
        let config = SigningSecretConfig {
            secret: Some("a".repeat(MIN_SECRET_LEN)),
            previous_secrets: vec!["b".repeat(MIN_SECRET_LEN)],
        };
        let keys = resolve_signing_keys(&config);
        assert_eq!(keys.previous.len(), 1);
        assert_eq!(
            keys.previous[0].as_ref(),
            "b".repeat(MIN_SECRET_LEN).as_bytes()
        );
    }

    #[test]
    fn resolved_keys_sign_and_verify_current() {
        let keys = ResolvedSigningKeys::new(b"current-key-32-bytes-xxxxxxxxxx".to_vec(), vec![]);
        let sig = keys.sign(b"test-message");
        assert!(keys.verify(b"test-message", &sig));
    }

    #[test]
    fn resolved_keys_verify_rejects_wrong_message() {
        let keys = ResolvedSigningKeys::new(b"current-key-32-bytes-xxxxxxxxxx".to_vec(), vec![]);
        let sig = keys.sign(b"message-a");
        assert!(!keys.verify(b"message-b", &sig));
    }

    #[test]
    fn resolved_keys_verify_previous_key_passes() {
        let old_key = b"old-key-32-bytes-xxxxxxxxxxxx!x".to_vec();
        let new_key = b"new-key-32-bytes-xxxxxxxxxxxx!x".to_vec();
        let old_keys = ResolvedSigningKeys::new(old_key.clone(), vec![]);
        let old_sig = old_keys.sign(b"session-id");
        let new_keys = ResolvedSigningKeys::new(new_key, vec![old_key]);
        assert!(new_keys.verify(b"session-id", &old_sig));
    }

    #[test]
    fn resolved_keys_verify_wrong_key_fails() {
        let keys_a = ResolvedSigningKeys::new(b"key-a-32-bytes-xxxxxxxxxxxxxxxx".to_vec(), vec![]);
        let keys_b = ResolvedSigningKeys::new(b"key-b-32-bytes-xxxxxxxxxxxxxxxx".to_vec(), vec![]);
        let sig = keys_a.sign(b"message");
        assert!(!keys_b.verify(b"message", &sig));
    }

    #[test]
    fn resolved_keys_sign_produces_64_char_hex() {
        let keys = ResolvedSigningKeys::new(b"key".to_vec(), vec![]);
        let sig = keys.sign(b"msg");
        assert_eq!(sig.len(), 64, "HMAC-SHA256 hex is 64 chars");
        assert!(sig.chars().all(|c| c.is_ascii_hexdigit()));
    }
}