boatramp-types 0.2.11

Shared, wasm-clean wire types + routing/config logic for boatramp (used by the server, CLI, and the edge Worker so the wire format and routing can't drift)
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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
//! Deploy-scoped configuration (the `routing` section of `project.cfg`).
//!
//! This is the **immutable, deploy-scoped** config tier: it is authored as the
//! `routing` section of `project.cfg`, parsed at `sync` time, and folded into
//! the deployment manifest (`boatramp_core::deploy::Manifest`).
//! Because it travels inside the manifest it is atomic with the content and
//! rolls back with it.
//!
//! (The mutable, site-scoped tier — domains, TLS, access control — is a separate
//! `SiteConfig` in the KV store, added alongside the virtualhost/auth work.)

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::error::ConfigError;
use crate::matcher::Pattern;

/// Deploy-scoped configuration — the `routing` section of `project.cfg`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DeployConfig {
    /// Schema version, pinned at [`crate::SCHEMA_VERSION`]. Optional in
    /// `project.cfg` routing (defaults to 1); always present once folded in.
    pub version: u32,
    /// Directory-index candidates, tried in order (default `["index.html"]`).
    pub index: Vec<String>,
    /// Map extensionless URLs to `.html` files (`/about` → `/about.html`).
    pub clean_urls: bool,
    /// Match the request path **case-insensitively** against redirects, rewrites,
    /// and static files (`/About.HTML` serves `/about.html`). Off by default
    /// (paths are case-sensitive); opt-in for case-folding origins.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub case_insensitive: bool,
    /// Trailing-slash policy.
    pub trailing_slash: TrailingSlash,
    /// Status code → error document (e.g. `404 → /404.html`).
    pub error_documents: BTreeMap<u16, String>,
    /// Redirect rules (first match wins).
    pub redirects: Vec<Redirect>,
    /// Rewrite rules (internal rewrite or proxy; first match wins).
    pub rewrites: Vec<Rewrite>,
    /// Response-header rules (all matching rules apply, in order).
    pub headers: Vec<HeaderRule>,
    /// Cache-Control defaults.
    pub cache: CacheConfig,
    /// Extension → MIME overrides (e.g. `.webmanifest`).
    pub mime_overrides: BTreeMap<String, String>,
    /// Allowed upstream hosts for proxy rewrites (exact host or `.suffix`
    /// match). When empty, proxying to any *public* host is allowed; private,
    /// loopback, link-local, and similar internal addresses are always blocked
    /// (SSRF guard), regardless of this list.
    pub proxy_allow: Vec<String>,
    /// WebAssembly request handlers (deploy-scoped).
    /// Matched before static lookup, after redirects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub handlers: Vec<HandlerConfig>,
    /// Message-consumer components, invoked per message on a topic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub consumers: Vec<ConsumerConfig>,
    /// Scheduled handler invocations (cron).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub crons: Vec<CronConfig>,
    /// Host-level SSE endpoints fanning out messaging topics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub streams: Vec<StreamConfig>,
}

impl Default for DeployConfig {
    fn default() -> Self {
        Self {
            version: crate::SCHEMA_VERSION,
            index: vec!["index.html".to_string()],
            clean_urls: false,
            case_insensitive: false,
            trailing_slash: TrailingSlash::default(),
            error_documents: BTreeMap::new(),
            redirects: Vec::new(),
            rewrites: Vec::new(),
            headers: Vec::new(),
            cache: CacheConfig::default(),
            mime_overrides: BTreeMap::new(),
            proxy_allow: Vec::new(),
            handlers: Vec::new(),
            consumers: Vec::new(),
            crons: Vec::new(),
            streams: Vec::new(),
        }
    }
}

impl DeployConfig {
    /// Parse a deploy-scoped `routing` document (RON). `implicit_some` is enabled
    /// so optional fields can be written as bare values (not `Some("...")`).
    pub fn from_ron(text: &str) -> Result<Self, ConfigError> {
        let options = ron::Options::default()
            .with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME);
        let config: Self = options
            .from_str(text)
            .map_err(|err| ConfigError::parse(err.to_string()))?;
        config.compile_check()?;
        Ok(config)
    }

    /// Whether `host` is permitted as a proxy-rewrite upstream by the
    /// `proxy_allow` list. An empty list permits any host (the separate
    /// public-IP SSRF guard still applies); otherwise the host must equal an
    /// entry or be a subdomain of a `.`-prefixed suffix entry.
    pub fn proxy_host_allowed(&self, host: &str) -> bool {
        if self.proxy_allow.is_empty() {
            return true;
        }
        let host = host.trim_end_matches('.').to_ascii_lowercase();
        self.proxy_allow.iter().any(|entry| {
            let entry = entry.trim().to_ascii_lowercase();
            match entry.strip_prefix('.') {
                Some(suffix) => host == suffix || host.ends_with(&format!(".{suffix}")),
                None => host == entry,
            }
        })
    }

    /// Verify every route/header pattern compiles. Used by `from_ron` and the
    /// `validate` subcommand so bad patterns fail fast at deploy time.
    pub fn compile_check(&self) -> Result<(), ConfigError> {
        for redirect in &self.redirects {
            Pattern::compile(&redirect.from)?;
            if let Some(when) = &redirect.when {
                crate::predicate::Predicate::compile(when)?;
            }
            if crate::predicate::Template::is_template(&redirect.to) {
                crate::predicate::Template::compile(&redirect.to)?;
            }
        }
        for rewrite in &self.rewrites {
            Pattern::compile(&rewrite.from)?;
            if let Some(when) = &rewrite.when {
                crate::predicate::Predicate::compile(when)?;
            }
            if crate::predicate::Template::is_template(&rewrite.to) {
                crate::predicate::Template::compile(&rewrite.to)?;
            }
        }
        for header in &self.headers {
            Pattern::compile(&header.matches)?;
        }
        self.check_handlers()?;
        Ok(())
    }

    /// Offline validation of the handler/consumer/cron/stream config: route
    /// patterns compile, HTTP methods and requested imports are recognized,
    /// cron schedules parse, and every cron route is served by some declared
    /// handler. (Component *binary* validation happens at `sync`, where the
    /// `.wasm` bytes are available.)
    fn check_handlers(&self) -> Result<(), ConfigError> {
        let handler_patterns: Vec<Pattern> = self
            .handlers
            .iter()
            .map(|h| Pattern::compile(&h.route))
            .collect::<Result<_, _>>()?;

        for handler in &self.handlers {
            if handler.component.is_empty() {
                return Err(ConfigError::parse(format!(
                    "handler {} has an empty component path",
                    handler.route
                )));
            }
            for method in &handler.methods {
                check_http_method(method)?;
            }
            for import in &handler.imports {
                check_import(import)?;
            }
            // `env` is for static, non-secret strings; a secret belongs in
            // `[handlers].secrets` as a *reference* to a host env var, so it
            // never lands in the (content-addressed, stored) manifest.
            // Best-effort heuristic — catches accidents.
            for (key, value) in &handler.env {
                if looks_like_secret(value) {
                    return Err(ConfigError::parse(format!(
                        "handler {} env var {key:?} looks like a secret; move it to \
                         [handlers].secrets as a reference to a host env var rather than \
                         inlining it in `env` (which is stored in the manifest)",
                        handler.route
                    )));
                }
            }
        }
        for consumer in &self.consumers {
            if consumer.topic.is_empty() || consumer.component.is_empty() {
                return Err(ConfigError::parse(
                    "consumer needs a non-empty topic and component".to_string(),
                ));
            }
            for import in &consumer.imports {
                check_import(import)?;
            }
        }
        for cron in &self.crons {
            check_cron_schedule(&cron.schedule)?;
            if !handler_patterns.iter().any(|p| p.is_match(&cron.route)) {
                return Err(ConfigError::parse(format!(
                    "cron route {} is not served by any declared handler",
                    cron.route
                )));
            }
        }
        for stream in &self.streams {
            Pattern::compile(&stream.route)?;
            if stream.topics.is_empty() {
                return Err(ConfigError::parse(format!(
                    "stream {} subscribes to no topics",
                    stream.route
                )));
            }
        }
        Ok(())
    }
}

/// The standard interface vocabulary a handler may request.
/// `sql` is the one generic non-`wasi:` interface.
const KNOWN_IMPORTS: &[&str] = &[
    "sql",
    "invoke",
    "wasi:http",
    "wasi:io",
    "wasi:keyvalue",
    "wasi:blobstore",
    "wasi:messaging",
    "wasi:clocks",
    "wasi:random",
    "wasi:logging",
];

/// Best-effort heuristic: does `value` look like a credential that should be a
/// `secrets` reference rather than a static `env` string?
/// Catches the common accidents — it is a guard, not a guarantee.
fn looks_like_secret(value: &str) -> bool {
    let v = value.trim();
    // A PEM private-key block.
    if v.contains("-----BEGIN") && v.contains("PRIVATE KEY") {
        return true;
    }
    // Well-known credential prefixes (cloud keys, VCS/chat/LLM tokens, …).
    const PREFIXES: &[&str] = &[
        "AKIA",
        "ASIA",
        "ghp_",
        "gho_",
        "ghu_",
        "ghs_",
        "github_pat_",
        "xoxb-",
        "xoxp-",
        "xoxa-",
        "glpat-",
        "AIza",
        "AccountKey=",
    ];
    if PREFIXES.iter().any(|p| v.contains(p)) {
        return true;
    }
    let has_digit = v.bytes().any(|b| b.is_ascii_digit());
    // A long pure-hex blob (API key / hash-shaped secret).
    if v.len() >= 40 && has_digit && v.bytes().all(|b| b.is_ascii_hexdigit()) {
        return true;
    }
    // A long, mixed-case, token-charset, high-entropy string (base64-ish key).
    let charset_ok = v
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'-' | b'_'));
    let mixed_case =
        v.bytes().any(|b| b.is_ascii_uppercase()) && v.bytes().any(|b| b.is_ascii_lowercase());
    v.len() >= 32 && charset_ok && has_digit && mixed_case && shannon_entropy_bits(v) >= 3.5
}

/// Shannon entropy of `s` in bits per character (0 for empty).
fn shannon_entropy_bits(s: &str) -> f64 {
    if s.is_empty() {
        return 0.0;
    }
    let mut counts = [0u32; 256];
    for b in s.bytes() {
        counts[b as usize] += 1;
    }
    let len = s.len() as f64;
    counts
        .iter()
        .filter(|&&c| c > 0)
        .map(|&c| {
            let p = c as f64 / len;
            -p * p.log2()
        })
        .sum()
}

/// Whether `import` is a **named SQL binding** grant: `sql:<name>` (a specific database) or
/// `sql:*` (every named database the site exposes). The bare `sql` (in `KNOWN_IMPORTS`) remains
/// the default database. A name is a conservative identifier so it can't smuggle a path or
/// injection through `sql.open(name)`.
fn is_named_sql_import(import: &str) -> bool {
    let Some(name) = import.strip_prefix("sql:") else {
        return false;
    };
    name == "*"
        || (!name.is_empty()
            && name
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
}

fn check_import(import: &str) -> Result<(), ConfigError> {
    if KNOWN_IMPORTS.contains(&import) || is_named_sql_import(import) {
        Ok(())
    } else {
        Err(ConfigError::parse(format!(
            "unknown handler import {import:?}; allowed: {}, or a named SQL binding `sql:<name>` / `sql:*`",
            KNOWN_IMPORTS.join(", ")
        )))
    }
}

fn check_http_method(method: &str) -> Result<(), ConfigError> {
    const METHODS: &[&str] = &["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
    if METHODS.contains(&method) {
        Ok(())
    } else {
        Err(ConfigError::parse(format!(
            "unknown HTTP method {method:?}"
        )))
    }
}

/// Validate a standard 5-field cron schedule (`minute hour dom month dow`).
/// Each field is `*`, `*/step`, a number, an `a-b` range, an `a-b/step`, or a
/// comma list of those, within the field's numeric bounds.
fn check_cron_schedule(schedule: &str) -> Result<(), ConfigError> {
    // Validation = parsing the schedule (the same parser the scheduler uses to
    // evaluate it — one grammar, no drift).
    crate::cron::CronSchedule::parse(schedule)
        .map(|_| ())
        .map_err(|err| ConfigError::parse(format!("cron schedule {schedule:?}: {err}")))
}

/// Trailing-slash handling for request paths.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrailingSlash {
    /// Leave the path as-is.
    #[default]
    Preserve,
    /// Redirect to add a trailing slash.
    Always,
    /// Redirect to strip a trailing slash.
    Never,
}

/// A redirect rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Redirect {
    /// Source pattern (see [`crate::matcher`]).
    pub from: String,
    /// Destination, with `:name`/`:splat` substitution.
    pub to: String,
    /// HTTP status (default 308 — permanent, method-preserving).
    #[serde(default = "default_redirect_status")]
    pub status: u16,
    /// Optional server-side condition (a [`crate::predicate`] expression over the
    /// request — `Accept-Language`, cookies, headers, `file_exists(...)`, …). When
    /// set, the rule fires only if it evaluates true. Compiled + type-checked at
    /// `validate`/`sync`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<String>,
}

fn default_redirect_status() -> u16 {
    308
}

/// A rewrite rule: serve a different path (internal) or proxy (absolute URL).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rewrite {
    /// Source pattern.
    pub from: String,
    /// Internal path or absolute proxy URL, with `:name`/`:splat` substitution.
    pub to: String,
    /// Status to serve for an internal rewrite (default 200).
    #[serde(default = "default_rewrite_status")]
    pub status: u16,
    /// Optional server-side condition — see [`Redirect::when`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<String>,
}

fn default_rewrite_status() -> u16 {
    200
}

/// A response-header rule applied to matching paths.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HeaderRule {
    /// Path pattern to match (named `matches` because `for` is a Rust keyword).
    pub matches: String,
    /// Headers to set.
    #[serde(default)]
    pub set: BTreeMap<String, String>,
    /// Header names to remove.
    #[serde(default)]
    pub unset: Vec<String>,
}

/// Cache-Control defaults.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CacheConfig {
    /// Default `Cache-Control` for responses not covered by a header rule.
    pub default: Option<String>,
}

/// A WebAssembly request handler bound to a route (deploy-scoped).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HandlerConfig {
    /// Route pattern (matcher syntax).
    pub route: String,
    /// HTTP methods this handler answers (empty = all).
    #[serde(default)]
    pub methods: Vec<String>,
    /// Path to the component `.wasm` within the deployment.
    pub component: String,
    /// Requested capabilities (interface names; see `KNOWN_IMPORTS`).
    #[serde(default)]
    pub imports: Vec<String>,
    /// Optional resource limits (capped by site config at activation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limits: Option<HandlerLimits>,
    /// Static environment variables (never secrets).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Function-to-function invoke allowlist (FI): the target names this handler may
    /// call through the `invoke` capability (same contract as
    /// [`FunctionConfig::invoke_targets`](crate::function::FunctionConfig)). Each entry
    /// may use `*` wildcards (`*` = any function, `img-*` = a family, `resize` = one
    /// literal). Deny by default: empty ⇒ the handler cannot invoke anything, even if it
    /// imports `invoke`. Only consulted when `imports` contains `invoke` and the site's
    /// `allow_imports` permits it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invoke_targets: Vec<String>,
}

/// Per-handler resource limits.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HandlerLimits {
    /// Max linear memory, MiB.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_mb: Option<u32>,
    /// Wall-clock timeout, milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u32>,
    /// CPU budget in wasmtime **fuel** units (instruction-count proxy); the
    /// guest traps when it runs out. A deterministic CPU bound on top of the
    /// wall-clock timeout. Omitted = unmetered.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fuel: Option<u64>,
}

/// Where a **new** consumer group starts consuming a topic (its initial cursor).
/// A group with no `group` name is the default work-queue and ignores this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StartPosition {
    /// Only events published from the group's first subscription onward (the
    /// conventional default; prior history is not replayed).
    #[default]
    Latest,
    /// Every event still retained on the topic, oldest-first (replay the backlog).
    Earliest,
}

/// A message-consumer component, invoked per message on a topic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConsumerConfig {
    /// Topic to subscribe to (namespaced like all topics).
    pub topic: String,
    /// Path to the component `.wasm` within the deployment.
    pub component: String,
    /// Requested capabilities.
    #[serde(default)]
    pub imports: Vec<String>,
    /// Consumer **group**: empty (default) = the competing-consumer work-queue
    /// (one of the site's consumers processes each message); a non-empty name = a
    /// durable fan-out subscriber that receives *every* message on the topic
    /// independently of other groups. Two consumers with different groups on one
    /// topic each get every message.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub group: String,
    /// Where a non-empty `group` starts on first subscription (`latest` |
    /// `earliest`). Ignored for the default work-queue.
    #[serde(default, skip_serializing_if = "crate::config::is_default_start")]
    pub start: StartPosition,
}

/// serde `skip_serializing_if` helper: a `Latest` start is the default and elided.
pub fn is_default_start(s: &StartPosition) -> bool {
    *s == StartPosition::default()
}

/// A scheduled invocation of a declared handler route.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CronConfig {
    /// Standard 5-field cron schedule.
    pub schedule: String,
    /// Handler route to invoke (must be served by a declared handler).
    pub route: String,
    /// Overlap policy when a previous run is still in flight.
    #[serde(default)]
    pub overlap: Overlap,
}

/// Cron overlap policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Overlap {
    /// Skip the tick if the previous invocation is still running (default).
    #[default]
    Skip,
    /// Allow concurrent invocations.
    Allow,
}

/// A host-level SSE (or WebSocket) endpoint fanning out messaging topics.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StreamConfig {
    /// Route the SSE (or WebSocket) endpoint is served at.
    pub route: String,
    /// Topics whose messages are broadcast to connected clients (server→client).
    pub topics: Vec<String>,
    /// Serve this route as a **WebSocket** instead of SSE:
    /// the same `topics` fan out server→client, and — bidirectionally — messages
    /// the client sends are published to [`publish_topic`](Self::publish_topic).
    /// Off by default (SSE).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub websocket: bool,
    /// For a `websocket` stream, the (scope-relative) topic that client→server
    /// messages are published to. `None` = the socket is receive-only (client
    /// sends are dropped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publish_topic: Option<String>,
}

/// Site-scoped, mutable configuration stored in the KV (not in the manifest).
///
/// Carries domains (virtualhost routing) and visitor access control; TLS,
/// previews, and retention land with their respective workstreams.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SiteConfig {
    /// Schema version, pinned at [`crate::SCHEMA_VERSION`].
    pub version: u32,
    /// Hostnames this site answers to.
    pub domains: DomainConfig,
    /// Transport security: HTTPS redirect + HSTS (site tier).
    #[serde(default)]
    pub security: SecurityConfig,
    /// Visitor access control (basic auth, IP rules, rate limiting).
    #[serde(default)]
    pub access: crate::access::AccessConfig,
    /// WebAssembly handler caps + import allowlist (site-scoped).
    /// `None` = handlers disabled for the site.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handlers: Option<HandlersSiteConfig>,
    /// On-the-fly response compression. Off by default;
    /// complements the precompressed-variant path for dynamic/unvaried responses.
    #[serde(default, skip_serializing_if = "CompressionConfig::is_default")]
    pub compression: CompressionConfig,
    /// Reverse-proxy gateway for publishing private services.
    /// `None` = no gateway routes. Declaring an upstream here is what authorizes
    /// reaching a private address (the SSRF guard stays public-only otherwise).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gateway: Option<crate::gateway::GatewayConfig>,
}

impl Default for SiteConfig {
    fn default() -> Self {
        Self {
            version: crate::SCHEMA_VERSION,
            domains: DomainConfig::default(),
            security: SecurityConfig::default(),
            access: crate::access::AccessConfig::default(),
            handlers: None,
            compression: CompressionConfig::default(),
            gateway: None,
        }
    }
}

/// On-the-fly compression policy. Opt-in: compresses a
/// response *only* when it has no precompressed variant / existing
/// `Content-Encoding`, its type is compressible, and (when known) its length is
/// at least `min_size`. Credentialed responses are skipped (BREACH safety).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CompressionConfig {
    /// Master toggle (default off).
    pub enabled: bool,
    /// Don't compress a response whose `Content-Length` is below this (bytes).
    /// Streaming responses with no declared length are always eligible.
    pub min_size: u64,
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            min_size: 1024,
        }
    }
}

impl CompressionConfig {
    fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

/// Site-scoped handler policy: the capability allowlist and resource caps that
/// a deployment's requested handler config is intersected against at
/// activation (deny by default).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlersSiteConfig {
    /// Whether handlers run for this site at all.
    pub enabled: bool,
    /// Interfaces handlers on this site may import (subset of `KNOWN_IMPORTS`).
    pub allow_imports: Vec<String>,
    /// Cap on per-handler memory (MiB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_memory_mb: Option<u32>,
    /// Cap on per-handler timeout (ms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_timeout_ms: Option<u32>,
    /// Cap on concurrent invocations for the site.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_concurrency: Option<u32>,
    /// Cap on per-handler CPU **fuel** (instruction-count proxy). A per-handler
    /// `fuel` may only lower this, never raise it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fuel: Option<u64>,
    /// Env-var name → secret reference, injected at instantiation (the value is
    /// a backend reference, resolved server-side — never a literal secret here).
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub secrets: BTreeMap<String, String>,
    /// Named aliases (besides the live/current deployment) whose deployments
    /// also run **background work** — consumers and crons. The
    /// current deployment always runs background work; previews never do. Empty
    /// by default, so only the current deployment is background-active. Each
    /// listed alias gets its own topic namespace (`{site}/{alias}/…`), isolated
    /// from the live one (e.g. opt `staging` in).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_aliases: Vec<String>,
    /// Cap on concurrent SSE stream connections for the site.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_stream_connections: Option<u32>,
    /// Cap on captured guest log lines per second for the site, so a noisy guest
    /// can't flood the log sink. Lines over the cap are
    /// dropped (counted). `None` = the server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_log_rate: Option<u32>,
    /// Opt **out** of capturing the site's guest `stdout`/`stderr` + `wasi:logging`. Capture is
    /// **on by default** (served via the logs endpoint + SSE tail, mirrored to `serve.log`); set
    /// this `true` to disable it — e.g. when a guest's output may carry secrets/PII. When
    /// disabled, the guest's stdio is discarded and never reaches the store, the logs API, or
    /// `serve.log`. (Inverted so the default — capture on — matches `Default`.)
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub disable_log_capture: bool,
    /// Edge response cache. Off unless present + `enabled`. When on, a
    /// cacheable `GET`/`HEAD` response the handler opts in via
    /// `Cache-Control: max-age=…` is stored and served for later identical
    /// requests **without re-instantiating the handler**. Never caches a private
    /// response (`no-store`/`private`, `Set-Cookie`, `Vary: *`, or an
    /// `Authorization` request without `public`/`s-maxage`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache: Option<HandlerCacheConfig>,
    /// GraphQL edge query-guard. Off unless present + `enabled`. When on, an
    /// incoming GraphQL operation is parsed at the edge and rejected **before the
    /// handler runs** if it exceeds the depth or complexity limit, or (unless
    /// allowed) is a schema-introspection query. Defense-in-depth over the fuel cap.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphql: Option<HandlerGraphqlConfig>,
    /// Browser cookie session auth. Off unless present. When set, a request with the named
    /// cookie but **no** `Authorization` header is authenticated from the cookie value: it
    /// becomes the app bearer token everywhere the header bearer already flows (managed
    /// handlers, the GraphQL edge, the data connector, invoked functions, `graphql::run`). The
    /// `Authorization` header always wins, so API clients are unaffected. boatramp **only reads**
    /// the cookie — the app's auth handler issues + refreshes it. Set it `HttpOnly; Secure;
    /// SameSite=Lax` (Lax is a CSRF requirement — the browser half of the defense) with a
    /// `__Host-` name prefix; and keep cookie-auth `GET`/`HEAD` handlers side-effect-free (a
    /// same-origin top-level navigation passes the CSRF gate). A cookie-authenticated request is
    /// CSRF-checked: same-origin always passes, and `allowed_origins` adds any cross-origins.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cookie_auth: Option<CookieAuthConfig>,
}

/// Browser cookie session auth for a site (see [`HandlersSiteConfig::cookie_auth`]). boatramp
/// only **reads** the cookie; the app sets it. The cookie value is the app bearer token, opaque
/// to boatramp (the app's own `Authorizer` / OIDC config verifies it, exactly as for a header
/// bearer).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CookieAuthConfig {
    /// The cookie whose value is used as the bearer when no `Authorization` header is present.
    pub cookie_name: String,
    /// The **additional cross-origin** CSRF allowlist. A **same-origin** request (its `Origin`
    /// authority equals the request's own `Host`) is always allowed — a page calling its own
    /// origin, the normal SPA case, is definitionally CSRF-safe. This list adds the *other*
    /// origins a browser app served from a **different** origin than this API may come from; each
    /// entry is a scheme+host[+port] origin, e.g. `https://app.example.com`. A cross-origin
    /// request whose `Origin` (or, absent that, `Referer`) is not same-origin and **not** listed
    /// is rejected. **Empty ⇒ same-origin only** — the common case needs no configuration.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed_origins: Vec<String>,
}

/// Per-site GraphQL edge query-guard tuning (see [`HandlersSiteConfig::graphql`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlConfig {
    /// Master switch. `false` (the default) ⇒ the guard is inert even if present.
    pub enabled: bool,
    /// Deepest allowed selection-set nesting (fragments expanded). `None` ⇒ the
    /// server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_depth: Option<u32>,
    /// Largest allowed total field count (a schema-free complexity proxy). `None` ⇒
    /// the server default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_complexity: Option<u32>,
    /// Whether a schema-introspection query is allowed. `None` ⇒ the posture default
    /// (**off** under the multi-tenant posture, on for single-tenant).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub introspection: Option<bool>,
    /// Automatic Persisted Queries: clients may send a query hash
    /// (`extensions.persistedQuery.sha256Hash`) instead of the full query; the edge
    /// resolves + caches `hash → query` (saving bandwidth + parse cost).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub persisted_queries: bool,
    /// Safelist mode: only pre-registered query hashes run (a query allowlist); the edge
    /// never registers a new query. Implies (and is stronger than) `persisted_queries`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub safelist: bool,
    /// Federation gateway: this site is a supergraph gateway. A GraphQL query is planned
    /// against the project's registered subgraphs and executed by dispatching fetches to
    /// the subgraph functions (a subgraph's name is its function name), stitching the
    /// results — instead of running a single handler component.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub federated: bool,
    /// Serve the GraphiQL in-browser explorer: a browser `GET` (an `Accept: text/html`
    /// request) to the endpoint gets the IDE, which posts queries back to the same URL.
    /// A developer convenience — off by default; pair with `introspection` for schema docs.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub graphiql: bool,
    /// Declarative data connector: serve the GraphQL API by generating it from a managed
    /// database (queries compiled to SQL) instead of running a wasm handler. Absent unless
    /// configured; exposure is deny-by-default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<HandlerGraphqlDataConfig>,
}

/// The declarative GraphQL data connector's configuration (see
/// [`HandlerGraphqlConfig::data`]). A database-derived API is **deny-by-default**: only the
/// tables (and their columns) named here are exposed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlDataConfig {
    /// Master switch. `false` (the default) ⇒ the connector is inert even if present.
    pub enabled: bool,
    /// The managed SQL database name to expose (the site's default database if unset).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub source: String,
    /// The exposed tables, keyed by table name. Deny-by-default: a table absent here is
    /// neither in the generated schema nor queryable.
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub tables: std::collections::BTreeMap<String, HandlerGraphqlTableConfig>,
    /// Allow mutations (insert/update/delete). Off by default — the connector is read-only
    /// unless a site opts in.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub mutations: bool,
    /// Bind `row_filter` claims from a **verified application bearer token** (the app's own
    /// IdP), not only the host-asserted `project`. This unlocks multi-tenant-within-one-project
    /// isolation: the app's tokens carry a tenant claim (e.g. `tid`) a `row_filter` scopes rows
    /// by. A claim value is used **only** from a fully verified token; a missing/invalid token
    /// leaves the claim absent, so a filter referencing it denies (never widens). Absent ⇒ only
    /// the host `project` claim is available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub claims_from_token: Option<HandlerGraphqlTokenClaims>,
}

/// How to verify an application bearer token whose claims a `row_filter` may bind (see
/// [`HandlerGraphqlDataConfig::claims_from_token`]). The token is verified against `issuer` +
/// the JWKS (signature, `iss`, `exp`/`nbf`, `kid`); on success its scalar claims are merged in
/// beside the host-asserted `project` (which a token can never override).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlTokenClaims {
    /// The expected token issuer (`iss`).
    pub issuer: String,
    /// A **host environment variable** holding the app IdP's JWKS JSON — the operator maps
    /// the app's public JWKS in, exactly like a handler secret. Re-read per request, so a
    /// rotated JWKS takes effect without a restart.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwks_env: Option<String>,
    /// Or a **URL** to fetch the JWKS from (cached per `kid`, refreshed on an unknown `kid` for
    /// IdP key rollover). Operator-configured, so not a request-controlled fetch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jwks_url: Option<String>,
    /// An optional expected audience (`aud`); unset skips audience validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audience: Option<String>,
}

/// One exposed table's policy (see [`HandlerGraphqlDataConfig::tables`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlTableConfig {
    /// The readable columns (an allow-list). Deny-by-default: a column absent here is
    /// invisible.
    pub columns: Vec<String>,
    /// Row-level filter terms, all applied to every access — the tenant-isolation seam.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub row_filter: Vec<HandlerGraphqlRowTerm>,
    /// Fields on this type resolved by a **wasm function** instead of a column: `field →
    /// function name`. The connector resolves the row's columns from SQL, then batches one
    /// invoke to the function (a local `_entities` fetch) to fill the field. This map is also
    /// the allowlist — only these fields delegate, only to these functions.
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub resolvers: std::collections::BTreeMap<String, String>,
}

/// One row-filter term: the `column` must equal the value of the request's `claim` (see
/// [`HandlerGraphqlTableConfig::row_filter`]). Claims are host-asserted (e.g. `project`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerGraphqlRowTerm {
    /// The constrained column.
    pub column: String,
    /// The request claim whose value the column must equal.
    pub claim: String,
}

/// Per-site edge response-cache tuning (see [`HandlersSiteConfig::cache`]).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HandlerCacheConfig {
    /// Master switch. `false` (the default) ⇒ the cache is inert even if present.
    pub enabled: bool,
    /// Largest cacheable entry (encoded status+headers+body), in bytes; a bigger
    /// response streams through uncached. `None` ⇒ the server default (256 KiB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_entry_bytes: Option<u64>,
    /// Upper bound (seconds) on a stored entry's TTL, clamping an over-long
    /// `max-age`. `None` ⇒ the server default (3600s).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_ttl_secs: Option<u64>,
}

impl SiteConfig {
    /// Parse from JSON (the KV storage / API format).
    pub fn from_json(bytes: &[u8]) -> Result<Self, ConfigError> {
        serde_json::from_slice(bytes).map_err(|err| ConfigError::parse(err.to_string()))
    }

    /// Serialize to JSON for KV storage.
    pub fn to_json(&self) -> Result<Vec<u8>, ConfigError> {
        serde_json::to_vec(self).map_err(|err| ConfigError::parse(err.to_string()))
    }
}

/// The hostnames a site answers to.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DomainConfig {
    /// Primary/canonical hostname (e.g. `example.com`).
    pub primary: Option<String>,
    /// Additional exact hostnames (e.g. `www.example.com`).
    pub aliases: Vec<String>,
    /// Wildcard patterns (`*.example.com`), matched by suffix at any depth.
    pub wildcards: Vec<String>,
    /// Redirect exact-alias hosts to [`primary`](Self::primary) with a 301
    /// (apex↔www canonicalization). Only exact aliases redirect — wildcard hosts
    /// serve as-is. Off by default.
    pub canonical_redirect: bool,
}

impl DomainConfig {
    /// All exact hostnames (primary first, then aliases).
    pub fn exact_hosts(&self) -> impl Iterator<Item = &str> {
        self.primary
            .as_deref()
            .into_iter()
            .chain(self.aliases.iter().map(String::as_str))
    }
}

/// Site-scoped **transport security** (the site config tier owns transport
/// concerns). Off by default; the operator opts in once TLS is in
/// front (directly or via a terminating proxy).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SecurityConfig {
    /// 301 plain-HTTP requests to HTTPS. Proxy-aware: the effective scheme is
    /// read from `X-Forwarded-Proto` behind a TLS-terminating proxy.
    pub https_redirect: bool,
    /// Send `Strict-Transport-Security` on HTTPS responses, when set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hsts: Option<Hsts>,
    /// `Content-Security-Policy` header value, when set (opt-in: a default CSP
    /// would break the inline scripts/styles common in static sites, so the
    /// operator supplies the policy). Applied on host-routed responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub csp: Option<String>,
    /// `X-Frame-Options` header value (e.g. `DENY`, `SAMEORIGIN`), when set.
    /// Opt-in: it can break legitimate embedding, so it isn't a default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frame_options: Option<String>,
}

/// HTTP Strict-Transport-Security policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Hsts {
    /// `max-age` in seconds.
    pub max_age: u64,
    /// Apply to subdomains too.
    pub include_subdomains: bool,
    /// Request inclusion in browser preload lists.
    pub preload: bool,
}

impl Default for Hsts {
    fn default() -> Self {
        // One year + includeSubDomains: the common safe baseline (preload is an
        // explicit opt-in since it's hard to undo).
        Self {
            max_age: 31_536_000,
            include_subdomains: true,
            preload: false,
        }
    }
}

impl Hsts {
    /// The `Strict-Transport-Security` header value.
    pub fn header_value(&self) -> String {
        let mut v = format!("max-age={}", self.max_age);
        if self.include_subdomains {
            v.push_str("; includeSubDomains");
        }
        if self.preload {
            v.push_str("; preload");
        }
        v
    }
}

/// Compute the canonicalization/HTTPS **redirect target** for a request, or
/// `None` if it's already canonical. `scheme` is the
/// effective scheme (`http`/`https`, proxy-aware), `host` the request host
/// (no port), `path_and_query` the rest of the URL. A single 301 collapses both
/// an HTTPS upgrade and an apex↔www redirect.
pub fn transport_redirect(
    security: &SecurityConfig,
    domains: &DomainConfig,
    scheme: &str,
    host: &str,
    path_and_query: &str,
) -> Option<String> {
    let target_scheme = if security.https_redirect && scheme == "http" {
        "https"
    } else {
        scheme
    };
    // Only exact aliases canonicalize to the primary; wildcard hosts serve as-is.
    let target_host = match &domains.primary {
        Some(primary)
            if domains.canonical_redirect
                && primary != host
                && domains.aliases.iter().any(|a| a == host) =>
        {
            primary.as_str()
        }
        _ => host,
    };
    if target_scheme == scheme && target_host == host {
        return None;
    }
    Some(format!("{target_scheme}://{target_host}{path_and_query}"))
}

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

    #[test]
    fn empty_config_uses_defaults() {
        let config = DeployConfig::from_ron("()").unwrap();
        assert_eq!(config.index, vec!["index.html".to_string()]);
        assert_eq!(config.trailing_slash, TrailingSlash::Preserve);
        assert!(config.redirects.is_empty());
    }

    #[test]
    fn transport_redirect_https_canonical_and_noop() {
        let mut domains = DomainConfig {
            primary: Some("example.com".into()),
            aliases: vec!["www.example.com".into()],
            ..Default::default()
        };
        let mut sec = SecurityConfig::default();

        // Defaults: nothing configured → no redirect.
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "example.com", "/a?b=1"),
            None
        );

        // HTTPS redirect only.
        sec.https_redirect = true;
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "example.com", "/a?b=1").as_deref(),
            Some("https://example.com/a?b=1")
        );
        // Already https → no-op.
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "example.com", "/a"),
            None
        );

        // Canonical: an exact alias → primary (and HTTPS in one hop).
        domains.canonical_redirect = true;
        assert_eq!(
            transport_redirect(&sec, &domains, "http", "www.example.com", "/p").as_deref(),
            Some("https://example.com/p")
        );
        // The primary itself is canonical → only the scheme may change.
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "example.com", "/p"),
            None
        );
        // A wildcard/non-alias host is NOT canonicalized (only the scheme).
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "blog.example.com", "/p"),
            None
        );
        sec.https_redirect = false;
        assert_eq!(
            transport_redirect(&sec, &domains, "https", "www.example.com", "/p").as_deref(),
            Some("https://example.com/p"),
            "canonical redirect applies even without https_redirect"
        );
    }

    #[test]
    fn hsts_header_value() {
        assert_eq!(
            Hsts::default().header_value(),
            "max-age=31536000; includeSubDomains"
        );
        assert_eq!(
            Hsts {
                max_age: 60,
                include_subdomains: false,
                preload: true
            }
            .header_value(),
            "max-age=60; preload"
        );
    }

    #[test]
    fn secret_heuristic_flags_credentials_not_plain_config() {
        // Plain, legitimate `env` values are NOT flagged.
        for ok in [
            "info",
            "production",
            "https://api.example.com/v1",
            "3000",
            "en-US,en;q=0.9",
            "a-normal-kebab-case-flag",
        ] {
            assert!(!looks_like_secret(ok), "false positive on {ok:?}");
        }
        // Credential-shaped values ARE flagged.
        let pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIabc\n-----END RSA PRIVATE KEY-----";
        for bad in [
            pem,
            "AKIAIOSFODNN7EXAMPLE",
            "ghp_16C7e42F292c6912E7710c838347Ae178B4a", // GitHub PAT shape
            "AIzaSyA-1234567890abcdefghijklmnopqrstuv", // Google API key shape
            "wJalrXUtnFEMI1bK7MDENGbPxRfiCYEXAMPLEKEY12", // mixed-case high-entropy
            "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef0123", // long hex
        ] {
            assert!(looks_like_secret(bad), "missed secret {bad:?}");
        }
    }

    #[test]
    fn check_handlers_rejects_secret_in_env() {
        use std::collections::BTreeMap;
        let config = DeployConfig {
            handlers: vec![HandlerConfig {
                route: "/h".into(),
                methods: Vec::new(),
                component: "h.wasm".into(),
                imports: Vec::new(),
                limits: None,
                env: BTreeMap::from([("AWS_KEY".to_string(), "AKIAIOSFODNN7EXAMPLE".to_string())]),
                invoke_targets: Vec::new(),
            }],
            ..Default::default()
        };
        let err = config.compile_check().unwrap_err().to_string();
        assert!(err.contains("looks like a secret"), "got: {err}");
    }

    #[test]
    fn parses_a_full_document() {
        let text = r#"(
            clean_urls: true,
            trailing_slash: Never,
            error_documents: { 404: "/404.html" },
            redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
            rewrites: [ (from: "/app/**", to: "/index.html") ],
            headers: [ (matches: "**.js", set: { "Cache-Control": "public, max-age=31536000, immutable" }) ],
            cache: ( default: "public, max-age=0, must-revalidate" ),
            mime_overrides: { ".webmanifest": "application/manifest+json" },
        )"#;
        let config = DeployConfig::from_ron(text).unwrap();
        assert!(config.clean_urls);
        assert_eq!(config.trailing_slash, TrailingSlash::Never);
        assert_eq!(config.redirects[0].status, 301);
        assert_eq!(config.rewrites[0].status, 200); // defaulted
        assert_eq!(
            config.error_documents.get(&404).map(String::as_str),
            Some("/404.html")
        );
    }

    #[test]
    fn rejects_bad_pattern_at_parse() {
        let text = r#"( redirects: [ (from: "/a/**/b/**", to: "/x") ] )"#;
        assert!(DeployConfig::from_ron(text).is_err());
    }

    #[test]
    fn rejects_unknown_field() {
        assert!(DeployConfig::from_ron("( nope: true )").is_err());
    }

    #[test]
    fn accepts_named_sql_imports_and_rejects_malformed_ones() {
        use super::check_import;
        // The bare capability + named-database grants are accepted.
        assert!(check_import("sql").is_ok());
        assert!(check_import("sql:product").is_ok());
        assert!(check_import("sql:privileged_2-a").is_ok());
        assert!(check_import("sql:*").is_ok());
        // Malformed named grants are rejected: empty name, or a name that could smuggle a path /
        // injection through `sql.open(name)`.
        assert!(check_import("sql:").is_err());
        assert!(check_import("sql:a/b").is_err());
        assert!(check_import("sql:a b").is_err());
        // A wholly-unknown import is still rejected.
        assert!(check_import("wasi:filesystem").is_err());
    }

    #[test]
    fn proxy_allow_list_matching() {
        // Empty list permits any host (the IP guard still applies separately).
        assert!(DeployConfig::default().proxy_host_allowed("anything.example"));

        let cfg = DeployConfig {
            proxy_allow: vec!["api.example.com".into(), ".internal.test".into()],
            ..DeployConfig::default()
        };
        assert!(cfg.proxy_host_allowed("api.example.com")); // exact
        assert!(cfg.proxy_host_allowed("API.EXAMPLE.COM")); // case-insensitive
        assert!(cfg.proxy_host_allowed("a.internal.test")); // suffix
        assert!(cfg.proxy_host_allowed("internal.test")); // suffix apex
        assert!(!cfg.proxy_host_allowed("evil.com"));
        assert!(!cfg.proxy_host_allowed("notapi.example.com"));
    }

    #[test]
    fn parses_handler_config() {
        let text = r#"(
            handlers: [
                ( route: "/api/orders/*", methods: ["GET", "POST"],
                  component: "handlers/orders.wasm",
                  imports: ["sql", "wasi:keyvalue", "wasi:messaging"],
                  limits: ( memory_mb: 64, timeout_ms: 10000 ),
                  env: { "LOG_LEVEL": "info" } ),
            ],
            consumers: [
                ( topic: "orders/created", component: "handlers/agg.wasm",
                  imports: ["sql"] ),
            ],
            crons: [ ( schedule: "0 */6 * * *", route: "/api/orders/reindex", overlap: Skip ) ],
            streams: [ ( route: "/events/orders", topics: ["orders/created"] ) ],
        )"#;
        let config = DeployConfig::from_ron(text).unwrap();
        assert_eq!(config.handlers.len(), 1);
        assert_eq!(config.handlers[0].imports.len(), 3);
        assert_eq!(
            config.handlers[0].limits.as_ref().unwrap().memory_mb,
            Some(64)
        );
        assert_eq!(config.consumers.len(), 1);
        assert_eq!(config.crons[0].overlap, Overlap::Skip);
        assert_eq!(config.streams[0].topics, vec!["orders/created".to_string()]);
    }

    #[test]
    fn site_config_round_trips_through_json_and_ron() {
        // A fully-populated SiteConfig, exercising the newer handler sub-configs (cache,
        // graphql, cookie_auth) that the API stores and returns. `SiteConfig` has
        // `deny_unknown_fields`, so any serde drift — a field that serializes under one name
        // but deserializes under another, or one that silently drops — makes the round-trip
        // fail to parse or fail equality. This is the guard for the "config field doesn't
        // round-trip" class (write a config, can't read it back).
        let cfg = SiteConfig {
            handlers: Some(HandlersSiteConfig {
                enabled: true,
                allow_imports: vec!["sql".into(), "graphql".into()],
                cache: Some(HandlerCacheConfig {
                    enabled: true,
                    max_entry_bytes: Some(262_144),
                    max_ttl_secs: Some(600),
                }),
                graphql: Some(HandlerGraphqlConfig {
                    enabled: true,
                    federated: true,
                    max_depth: Some(12),
                    safelist: true,
                    ..Default::default()
                }),
                cookie_auth: Some(CookieAuthConfig {
                    cookie_name: "__Host-session".into(),
                    allowed_origins: vec!["https://app.example.com".into()],
                }),
                ..Default::default()
            }),
            ..Default::default()
        };

        // JSON is the API wire format (PUT/GET /api/sites/:site/config); `from_json` is the
        // parser the server uses, so this exercises the exact path.
        let json = serde_json::to_vec(&cfg).unwrap();
        let from_json = SiteConfig::from_json(&json)
            .unwrap_or_else(|e| panic!("SiteConfig JSON round-trip failed to parse: {e}"));
        assert_eq!(
            from_json, cfg,
            "SiteConfig did not survive a JSON round-trip"
        );

        // And RON (via the derived Deserialize), the on-disk config format.
        let ron = ron::ser::to_string(&cfg).unwrap();
        let from_ron: SiteConfig = ron::from_str(&ron)
            .unwrap_or_else(|e| panic!("SiteConfig RON round-trip failed to parse: {e}\n{ron}"));
        assert_eq!(from_ron, cfg, "SiteConfig did not survive a RON round-trip");
    }

    #[test]
    fn handler_validation_rejects_bad_config() {
        // Unknown import.
        assert!(DeployConfig::from_ron(
            r#"( handlers: [ ( route: "/a", component: "a.wasm", imports: ["wasi:gpu"] ) ] )"#
        )
        .is_err());
        // Bad HTTP method.
        assert!(DeployConfig::from_ron(
            r#"( handlers: [ ( route: "/a", component: "a.wasm", methods: ["FETCH"] ) ] )"#
        )
        .is_err());
        // Cron route not served by any handler.
        assert!(DeployConfig::from_ron(
            r#"( handlers: [ ( route: "/a", component: "a.wasm" ) ],
                 crons: [ ( schedule: "* * * * *", route: "/nope" ) ] )"#
        )
        .is_err());
        // A cron whose route IS served validates.
        assert!(DeployConfig::from_ron(
            r#"( handlers: [ ( route: "/tasks/*", component: "a.wasm" ) ],
                 crons: [ ( schedule: "0 0 * * *", route: "/tasks/x" ) ] )"#
        )
        .is_ok());
    }

    #[test]
    fn cron_schedule_validation() {
        for ok in [
            "* * * * *",
            "0 */6 * * *",
            "30 2 1 1 0",
            "0,15,30,45 9-17 * * 1-5",
        ] {
            assert!(check_cron_schedule(ok).is_ok(), "{ok} should be valid");
        }
        for bad in [
            "* * * *",     // 4 fields
            "60 * * * *",  // minute out of range
            "* 24 * * *",  // hour out of range
            "* * 0 * *",   // dom < 1
            "* * * 13 *",  // month > 12
            "*/0 * * * *", // zero step
            "5-1 * * * *", // descending range
        ] {
            assert!(check_cron_schedule(bad).is_err(), "{bad} should be invalid");
        }
    }

    #[test]
    fn handler_free_config_omits_handler_fields() {
        // A static-only deploy serializes without any handler keys (so existing
        // manifest ids are unchanged).
        let json = serde_json::to_string(&DeployConfig::default()).unwrap();
        assert!(!json.contains("handlers"));
        assert!(!json.contains("crons"));
    }

    #[test]
    fn schema_version_defaults_to_one() {
        // Optional in RON; defaults to 1.
        assert_eq!(DeployConfig::from_ron("()").unwrap().version, 1);
        assert_eq!(DeployConfig::from_ron("(version: 1)").unwrap().version, 1);
        assert_eq!(SiteConfig::default().version, 1);
        // A version-less stored SiteConfig still reads as v1.
        assert_eq!(SiteConfig::from_json(b"{}").unwrap().version, 1);
    }
}