cratefield-core 0.6.0

Cratefield harness kernel: Module trait, Harness builder, ports, errors
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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
//! Route protection policies and the production abuse gate (issue #133).
//!
//! Every declared write route carries an explicit [`RoutePolicy`]: it is
//! open, protected by a human-form CAPTCHA, or protected by a machine
//! signature (a provider webhook). The old shape — a bare `captcha: bool`
//! plus the module-level `public_writes()` flag consulted only by
//! `fz doctor` — let a webhook satisfy "has captcha" while simultaneously
//! getting a captcha widget rendered on it, and left production booting
//! with no verification at all as long as nobody ran the doctor.
//!
//! [`WriteGuards::collect`] reads the composed modules and says what the
//! venture demands; [`production_readiness`] turns that plus what the
//! runtime can actually do into build errors. `HarnessBuilder::build`
//! calls it — enforcement moved from a CLI report to runtime
//! initialization — and `fz doctor` keeps calling the same function as an
//! advisory re-check, the way it re-checks `harness_api` (issue #17).

use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::harness::Runtime;
use crate::module::Module;
use crate::ports::{Captcha, Port};
use crate::problem::Problem;
use crate::problems::SLUGS;
use crate::surface::{Audience, Surface};
use crate::venture::VentureEnv;

/// How a request to a declared route proves it is legitimate.
///
/// The variants are mutually exclusive by construction: a route is
/// protected by a human proof, a machine signature, an artifact this
/// service issued, or nothing — never two of them, and never by
/// whichever check the module happened to wire up.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum RoutePolicy {
    /// No gateway-level protection. The default, and correct for reads
    /// and for anything the handler authenticates itself.
    #[default]
    Open,
    /// A public form submission from a browser. The handler verifies the
    /// `captchaToken` the renderer supplies through the `Captcha` port,
    /// and `Harness::build` refuses to boot a production venture whose
    /// runtime cannot actually do that ([`captcha_effective`]).
    HumanForm,
    /// An authenticated machine caller — a provider webhook. The handler
    /// proves the delivery with the module's declared verifier
    /// ([`SignatureVerification`]: `Payments::verify_webhook` by default,
    /// or a `webhook_signature` scheme) plus the [`Inbox`] dedup ledger. A
    /// CAPTCHA is meaningless here (the caller has no browser) and must
    /// never be rendered or required on such a route.
    ///
    /// [`Payments::verify_webhook`]: crate::ports::Payments::verify_webhook
    /// [`Inbox`]: crate::idempotency::Inbox
    Signature,
    /// A public write whose proof is a single-use, purpose-bound
    /// artifact **this service issued**: a magic link, a passkey or OAuth
    /// challenge, an unsubscribe link (issue #143). The caller presents
    /// something only a prior request of ours could have produced, so the
    /// gate is the [`Signer`] key ring (issue #137), not a widget.
    ///
    /// This variant exists because the auth login methods had nowhere
    /// honest to sit. They are public writers with no ADR 0010 surface,
    /// so [`WriteGuards::collect`]'s conservative fallback filed them
    /// under CAPTCHA — and a passkey challenge will never render one. A
    /// production venture composing only auth modules therefore could not
    /// boot at all except through `fz doctor --allow-no-captcha`, an
    /// override the code itself documents as previews-only. This is not
    /// an exemption: it carries its own production requirement, a
    /// usable [`Signer`], because without one there is nothing to issue
    /// or verify the artifact with.
    ///
    /// [`Signer`]: crate::ports::Signer
    SignedLink,
    /// An authenticated developer caller (issue #532): the request
    /// presents `Authorization: Bearer <api key>` and the handler gates
    /// it through [`require_api_key`], which verifies the key's hash and
    /// checks one scope. A CAPTCHA is meaningless here (the caller is a
    /// machine) and must never be rendered or required on such a route —
    /// the same rule as [`RoutePolicy::Signature`].
    ///
    /// This variant carries no scope on purpose: a `RoutePolicy` is
    /// `Copy` + serde and travels through surface documents, so it
    /// cannot hold a per-action string. The route policy says *how* the
    /// route is guarded; the scope is the handler's per-request argument
    /// to `require_api_key`.
    ///
    /// [`require_api_key`]: crate::api_key::require_api_key
    ApiKey,
}

impl RoutePolicy {
    /// Whether this policy is a protection (as opposed to [`RoutePolicy::Open`]).
    #[must_use]
    pub fn is_guarded(self) -> bool {
        self != Self::Open
    }
}

/// Which verifier proves a module's [`RoutePolicy::Signature`] deliveries
/// (issue #533): the `Payments` port — the default every existing module was
/// built against — or the core `webhook_signature` HMAC scheme keyed by the
/// module's own config secret. The production gate demands whichever the
/// module named, never both and never neither.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureVerification {
    /// `Payments::verify_webhook` — the default; production requires an
    /// effective `Payments` port.
    Payments,
    /// A `webhook_signature` scheme keyed by a module-scoped config secret:
    /// `secret` is a [`ModuleConfig`](crate::config::ModuleConfig)
    /// **suffix**, read as `{MODULE}_{SECRET}` (`"WEBHOOK_SECRET"` on module
    /// `pos` is `POS_WEBHOOK_SECRET`). Production requires that key — see
    /// [`webhook_secret_readiness`] — and no `Payments` port.
    Hmac {
        /// The module-scoped config key suffix holding the shared secret.
        secret: &'static str,
    },
}

/// What the composed modules demand of the runtime, module by module.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WriteGuards {
    /// Modules with a [`RoutePolicy::HumanForm`]-guarded write (or the
    /// conservative fallback: [`public_writes`] and no declared policy at all).
    ///
    /// [`public_writes`]: Module::public_writes
    pub captcha_modules: Vec<String>,
    /// Modules with a [`RoutePolicy::Signature`]-guarded write (webhooks),
    /// however they verify them.
    pub signature_modules: Vec<String>,
    /// The signature modules that prove their deliveries through
    /// `Payments::verify_webhook` — the default [`SignatureVerification`].
    pub payments_signature_modules: Vec<String>,
    /// The signature modules proving their deliveries with a
    /// `webhook_signature` scheme (issue #533), paired with the
    /// [`ModuleConfig`](crate::config::ModuleConfig) **suffix** of the key
    /// holding each secret; [`Self::hmac_signature_secrets`] composes the
    /// full keys.
    pub hmac_signature_modules: Vec<(String, &'static str)>,
    /// Modules whose public writes are proved by an artifact this service
    /// issued ([`RoutePolicy::SignedLink`], issue #143).
    pub signed_link_modules: Vec<String>,
    /// Whether the composition exposes any **public write** at all
    /// (issue #437): a declared guarded action of any kind — a captcha
    /// form, a webhook, a signed link — or the module-level
    /// [`public_writes`] flag for modules that predate surfaces. Broader
    /// than the three lists above by design: a webhook is an
    /// unauthenticated endpoint too, and the rate-limiter leg of
    /// [`production_readiness`] cares that *something* is writable, not
    /// by which proof. A [`RoutePolicy::ApiKey`] write demands no
    /// `RateLimiter` here: per-key limiting happens only where a handler
    /// calls `check_rate_limit` with
    /// [`ApiKeyPrincipal::rate_limit_key`] and a limiter is wired.
    ///
    /// [`public_writes`]: Module::public_writes
    /// [`ApiKeyPrincipal::rate_limit_key`]: crate::api_key::ApiKeyPrincipal::rate_limit_key
    pub has_public_writes: bool,
    /// Whether any declared action is the **admin plane** (issue #437):
    /// an [`Audience::Admin`] action, or any path under `/admin`. An
    /// admin route's bearer token is guessed rather than submitted, so
    /// it needs a budget even when the venture has no public writes —
    /// which is why this is its own answer and not a byproduct of
    /// [`Self::has_public_writes`].
    pub has_admin_routes: bool,
}

impl WriteGuards {
    /// Reads each module's declared surface. A module whose surface has
    /// no policy-guarded write but still sets [`public_writes`] counts as
    /// needing a CAPTCHA — the undeclared-public-writer fallback keeps
    /// out-of-tree and surface-less modules (the auth crates predate
    /// ADR 0010 surfaces) under the same gate instead of silently
    /// exempting them.
    ///
    /// [`public_writes`]: Module::public_writes
    #[must_use]
    pub fn collect(modules: &[Arc<dyn Module>]) -> Self {
        let mut guards = Self::default();
        for module in modules {
            let surface: Surface = module.surface();
            let (mut form, mut signature) = Self::surface_flags(&surface);
            let mut signed_link = surface
                .actions
                .iter()
                .any(|action| action.policy == RoutePolicy::SignedLink);
            // The undeclared-public-writer fallback only applies when
            // nothing in the surface is guarded. What it falls back *to*
            // is the module's own answer (issue #143): a surface-less
            // module has no action to hang a policy on, so this is the
            // only place it can say what protects its writes. The default
            // is still `HumanForm`, so saying nothing changes nothing.
            if !form && !signature && !signed_link && module.public_writes() {
                match module.public_write_policy() {
                    RoutePolicy::Signature => signature = true,
                    RoutePolicy::SignedLink => signed_link = true,
                    // An API-key writer (issue #532) is guarded — it is
                    // never pulled into the captcha fallback — but it
                    // demands no runtime port (the key store is the
                    // app's) and no production-legible decision: its
                    // budget is the per-key limiter hook, not a boot
                    // gate.
                    RoutePolicy::ApiKey => {}
                    RoutePolicy::HumanForm | RoutePolicy::Open => form = true,
                }
            }
            if form {
                guards.captcha_modules.push(module.name().to_owned());
            }
            if signature {
                guards.signature_modules.push(module.name().to_owned());
                // Whichever verifier the module declared (issue #533).
                match module.signature_verification() {
                    SignatureVerification::Payments => {
                        guards
                            .payments_signature_modules
                            .push(module.name().to_owned());
                    }
                    SignatureVerification::Hmac { secret } => {
                        guards
                            .hmac_signature_modules
                            .push((module.name().to_owned(), secret));
                    }
                }
            }
            if signed_link {
                guards.signed_link_modules.push(module.name().to_owned());
            }
            // The limiter leg (issue #437) asks two broader questions
            // than the per-policy lists: is anything writable publicly
            // at all, and is there an admin plane to brute-force. The
            // path check is the surface validation rule (`Audience::Admin`
            // lives under `/admin`), applied in both directions so an
            // undeclared admin path is caught even when the audience is
            // missing.
            if form || signature || signed_link || module.public_writes() {
                guards.has_public_writes = true;
            }
            if Self::declares_admin_routes(&surface) {
                guards.has_admin_routes = true;
            }
        }
        guards
    }

    /// The guards a **declared surface** demands (issue #131). A sidecar's
    /// merged surface is not a [`Module`] this process can ask
    /// [`public_writes`](Module::public_writes) or
    /// [`signature_verification`](Module::signature_verification) of, so
    /// whatever the document declares is exactly what it needs, and its
    /// signature routes verify through `Payments`, the default (issue
    /// #533). Same per-action reading as [`Self::collect`]
    /// through the one [`Action::demands_captcha`] predicate and the one
    /// `declares_admin_routes` predicate — a sidecar's admin plane needs
    /// the limiter floor as much as an in-process module's.
    ///
    /// [`Action::demands_captcha`]: crate::surface::Action::demands_captcha
    #[must_use]
    pub fn from_surface(module: &str, surface: &Surface) -> Self {
        let (form, signature) = Self::surface_flags(surface);
        let signed_link = surface
            .actions
            .iter()
            .any(|action| action.policy == RoutePolicy::SignedLink);
        Self {
            captcha_modules: form.then(|| module.to_owned()).into_iter().collect(),
            signature_modules: signature.then(|| module.to_owned()).into_iter().collect(),
            payments_signature_modules: signature.then(|| module.to_owned()).into_iter().collect(),
            hmac_signature_modules: Vec::new(),
            signed_link_modules: signed_link.then(|| module.to_owned()).into_iter().collect(),
            has_public_writes: form || signature || signed_link,
            has_admin_routes: Self::declares_admin_routes(surface),
        }
    }

    /// Whether any action needs a captcha and whether any is a signature
    /// route. The `Open`-with-`captcha` legacy mirror resolves inside
    /// [`Action::demands_captcha`].
    fn surface_flags(surface: &Surface) -> (bool, bool) {
        let mut form = false;
        let mut signature = false;
        for action in &surface.actions {
            if action.demands_captcha() {
                form = true;
            }
            if action.policy == RoutePolicy::Signature {
                signature = true;
            }
        }
        (form, signature)
    }

    /// Whether the surface declares the admin plane: an
    /// [`Audience::Admin`](crate::surface::Audience::Admin) action, or any
    /// path under `/admin`. Both spellings, so an action whose audience was
    /// forgotten is still counted by where it sits — the same rule
    /// [`Surface::validate`] enforces, read here instead of trusted.
    ///
    /// [`Surface::validate`]: crate::surface::Surface::validate
    fn declares_admin_routes(surface: &Surface) -> bool {
        surface.actions.iter().any(|action| {
            action.audience == Audience::Admin
                || action.path == "/admin"
                || action.path.starts_with("/admin/")
        })
    }

    /// Whether any module proves a public write with an artifact this
    /// service issued, and so needs a usable [`Signer`] (issue #143).
    ///
    /// [`Signer`]: crate::ports::Signer
    #[must_use]
    pub fn needs_signer(&self) -> bool {
        !self.signed_link_modules.is_empty()
    }

    /// Whether any module needs the `Captcha` port.
    #[must_use]
    pub fn needs_captcha(&self) -> bool {
        !self.captcha_modules.is_empty()
    }

    /// Whether any module proves a public write with
    /// [`Payments::verify_webhook`](crate::ports::Payments). Since issue
    /// #533 this is no longer "some module receives signed webhooks": a
    /// module may declare [`SignatureVerification::Hmac`] and verify with
    /// the core `webhook_signature` scheme instead, and this answers
    /// `false` for it — its production requirement is its secret key, not a
    /// port (see [`webhook_secret_readiness`]). The `STRIPE_WEBHOOK_SECRET`
    /// doctor rule is keyed on this, correctly.
    #[must_use]
    pub fn needs_payments(&self) -> bool {
        !self.payments_signature_modules.is_empty()
    }

    /// The HMAC-verified signature modules and the **full** config key each
    /// reads its secret from, composed through
    /// [`ModuleConfig`](crate::config::ModuleConfig)'s `{MODULE}_{SUFFIX}`
    /// rule — the one place the prefix logic lives (issue #533).
    #[must_use]
    pub fn hmac_signature_secrets(&self) -> Vec<(String, String)> {
        self.hmac_signature_modules
            .iter()
            .map(|(module, suffix)| {
                let key = crate::config::ModuleConfig::new(module, &crate::config::EmptyConfig)
                    .key(suffix);
                (module.clone(), key)
            })
            .collect()
    }

    /// Whether any route in the composition needs a limiter sitting in
    /// front of it (issue #437): a public write or an admin route. The
    /// admin plane is enough on its own — a bearer token is guessed, not
    /// submitted, so a venture that publishes nothing still needs the
    /// budget before its `/admin/*` routes.
    #[must_use]
    pub fn needs_rate_limiter(&self) -> bool {
        self.has_public_writes || self.has_admin_routes
    }
}

/// Whether the runtime's `Captcha` port can really verify a token in
/// production: the port is provided **and**, when the adapter reports,
/// hostname-bound and not fail-open. An adapter that does not report
/// ([`Captcha::binding`] = `None`) counts as effective — presence is all
/// the harness can know about a third-party implementation; the adapter
/// contract carries the duty to fail closed per request.
///
/// [`Captcha::binding`]: crate::ports::Captcha::binding
#[must_use]
pub fn captcha_effective(runtime: Option<&Arc<dyn Runtime>>) -> bool {
    runtime.is_some_and(|runtime| runtime.effectively_configured(Port::Captcha))
}

/// Whether the runtime can verify webhook signatures for the
/// [`RoutePolicy::Signature`]-guarded routes whose modules verify through
/// `Payments` (the default): signature verification is the adapter's
/// per-request duty (`verify_webhook` + `Inbox`), and which secret it
/// checks against is deploy configuration. A module that declared
/// [`SignatureVerification::Hmac`] is not this function's business — its
/// production requirement is its secret key, checked by
/// [`webhook_secret_readiness`].
#[must_use]
pub fn payments_effective(runtime: Option<&Arc<dyn Runtime>>) -> bool {
    runtime.is_some_and(|runtime| runtime.effectively_configured(Port::Payments))
}

/// The boot-time leg for HMAC-verified signature modules (issue #533): in
/// production, each one's configured secret key must be present and
/// non-blank, or the module's handler refuses every delivery. The errors
/// name the module and the config key, never the value, and there is no
/// waiver: an operator who wants the endpoint unverified removes the
/// route, which is a build-time decision. Run by the boot gate
/// ([`Harness::router`](crate::Harness::router)'s readiness re-check),
/// which holds the deployment config; the build-time gate has none, so it
/// skips this leg — the same split as the overrides there.
#[must_use]
pub fn webhook_secret_readiness(
    env: VentureEnv,
    guards: &WriteGuards,
    config: &dyn crate::config::Config,
) -> Vec<String> {
    if env != VentureEnv::Production {
        return Vec::new();
    }
    guards
        .hmac_signature_secrets()
        .iter()
        .filter(|(_, key)| config.get(key).is_none_or(|value| value.trim().is_empty()))
        .map(|(module, key)| {
            format!(
                "production venture verifies `{module}` webhook signatures with the \
                 webhook_signature HMAC scheme but `{key}` is not set — its handler refuses \
                 every delivery until the provider's signing secret is configured"
            )
        })
        .collect()
}

/// The operator's reason, if they actually gave one.
///
/// `docs/SECURITY.md` puts it in four words — "A blank reason is not an
/// acceptance" — and `unprotected_writes_override` already enforced it
/// for `HARNESS_ALLOW_UNPROTECTED_WRITES`. The `fz doctor` flag reached
/// the same gate without it: `--allow-no-captcha ""` arrives as
/// `Some("")`, which waived a production abuse control and recorded an
/// empty reason for it. A waiver with nothing to answer for is the
/// silent default the gate exists to remove.
///
/// One function, so the two ways to the same waiver cannot disagree
/// again.
#[must_use]
pub fn stated_reason(reason: Option<&str>) -> Option<&str> {
    reason.map(str::trim).filter(|reason| !reason.is_empty())
}

/// Config key holding an operator's explicit, recorded acceptance that
/// this deployment serves guarded routes it cannot fully protect
/// (issue #143).
///
/// The value is the **reason**, and an empty one does not count: an
/// override with nothing to answer for is the silent default this issue
/// exists to remove. It is recorded through `tracing` on every boot, so
/// it appears wherever the operator ships logs, and `fz doctor` reports
/// it. It exists because the gate landed on ventures that had already
/// been serving unprotected for months — refusing their traffic outright
/// on the next deploy would trade a quiet hole for a loud outage without
/// anyone choosing it. Wire the missing port and delete the key.
pub const ALLOW_UNPROTECTED_WRITES: &str = "HARNESS_ALLOW_UNPROTECTED_WRITES";

/// The operator's recorded reason for serving guarded routes unprotected,
/// if they set one (issue #143).
#[must_use]
pub fn unprotected_writes_override(config: &dyn crate::config::Config) -> Option<String> {
    config
        .get(ALLOW_UNPROTECTED_WRITES)
        .and_then(|raw| stated_reason(Some(raw.as_str())).map(str::to_owned))
}

/// Config key holding an operator's explicit, recorded acceptance that
/// this deployment serves its public writes and admin routes with **no
/// resolved rate limiter** (issue #437). Same contract as
/// [`ALLOW_UNPROTECTED_WRITES`]: the value is the **reason**, and a blank
/// one does not count; the boot gate records it once, wherever the
/// operator ships logs. It exists because the limiter was opt-in — a
/// runtime that failed to resolve its binding degraded to no limiter and
/// served — and because the escape from that must be as deliberate as the
/// gap it accepts. Resolve the binding and delete the key.
pub const ALLOW_UNLIMITED_PUBLIC_ROUTES: &str = "HARNESS_ALLOW_UNLIMITED_PUBLIC_ROUTES";

/// The operator's recorded reason for serving public writes and admin
/// routes unlimited, if they set one (issue #437).
#[must_use]
pub fn unlimited_public_routes_override(config: &dyn crate::config::Config) -> Option<String> {
    config
        .get(ALLOW_UNLIMITED_PUBLIC_ROUTES)
        .and_then(|raw| stated_reason(Some(raw.as_str())).map(str::to_owned))
}

/// The environment this **deployment** runs in (issue #143).
///
/// A venture carries a compiled [`VentureEnv`] — a builder default the
/// operator cannot change without a rebuild — and a deployment carries
/// an `ENV` binding it can. Every production-only rule used to read the
/// compiled one alone, so a Worker deployed with `ENV = "production"`
/// over a venture that never called [`Venture::env`] ran with all of
/// them switched off. Neither source may downgrade the other: if either
/// says `Production`, this is production.
///
/// [`Venture::env`]: crate::venture::Venture::env
#[must_use]
pub fn deployed_env(compiled: VentureEnv, config: &dyn crate::config::Config) -> VentureEnv {
    let declared = config
        .get("ENV")
        .as_deref()
        .and_then(VentureEnv::parse)
        .unwrap_or_default();
    compiled.strictest(declared)
}

/// Whether the deployment's environment contradicts the compiled one
/// (issue #143). Not an error by itself — the stricter answer wins — but
/// it means the build-time gate ran against the wrong environment, so
/// the caller re-checks and says so.
#[must_use]
pub fn env_disagreement(compiled: VentureEnv, deployed: VentureEnv) -> Option<String> {
    (compiled != deployed).then(|| {
        format!(
            "this deployment declares ENV={} but the venture was compiled with \
             VentureEnv::{compiled:?}: the production readiness gate at build time ran \
             against the wrong environment. Treating it as {} — call \
             `.env(VentureEnv::{deployed:?})` on the venture so the build refuses what \
             the deployment cannot serve (issue #143)",
            deployed.as_str(),
            deployed.as_str(),
        )
    })
}

/// Whether the runtime can issue and verify the artifacts a
/// [`RoutePolicy::SignedLink`] route rests on (issue #143).
///
/// Like [`rate_limiter_effective`], the runtime's own, provisional
/// answer: the native and Cloudflare runtimes advertise [`Port::Signer`]
/// unconditionally and leave `ports.signer == None` with only a warning
/// when the harness configuration does not parse (issue #478). The boot
/// gate re-checks against the resolved port — [`production_readiness`]
/// takes it as its `signer_ready` parameter.
#[must_use]
pub fn signer_effective(runtime: Option<&Arc<dyn Runtime>>) -> bool {
    runtime.is_some_and(|runtime| runtime.effectively_configured(Port::Signer))
}

/// Whether the runtime has a limiter it can actually consult (issue #437).
///
/// This is the **runtime's own answer**, and a provisional one: it is all
/// the build-time gate and `fz doctor` can know, because neither holds the
/// resolved [`Ports`](crate::ports::Ports). A Cloudflare binding that is
/// named but fails to resolve still reports `true` here — the adapter
/// degrades to `ports.rate_limiter == None` with only a warning — so the
/// boot gate re-checks against the port the runtime actually handed over:
/// [`production_readiness`] takes that resolved answer as its
/// `rate_limiter_ready` parameter and never computes it from this.
#[must_use]
pub fn rate_limiter_effective(runtime: Option<&Arc<dyn Runtime>>) -> bool {
    runtime.is_some_and(|runtime| runtime.effectively_configured(Port::RateLimiter))
}

/// The production abuse-control gate (issue #133), as collected error
/// strings (the [`ConfigError`] convention: report every problem at
/// once). Empty for anything but `Production`.
///
/// The two overrides are deliberate, independent, recorded decisions:
/// `allow_no_captcha` (the `fz doctor` flag, and
/// `HARNESS_ALLOW_UNPROTECTED_WRITES` at the boot gate) downgrades only
/// the CAPTCHA refusal, and `allow_unlimited`
/// ([`ALLOW_UNLIMITED_PUBLIC_ROUTES`]) downgrades only the
/// rate-limiter refusal (issue #437). One key waiving two controls is how
/// the second stays unwired after the first is fixed.
///
/// The limiter leg is keyed on `rate_limiter_ready`, the **resolved**
/// answer, and never inferred from [`Runtime::provides`]: the Cloudflare
/// runtime reports [`Port::RateLimiter`] from a configured binding *name*,
/// and a binding that fails to resolve degrades to
/// `ports.rate_limiter == None` with only a `warn_once`. Callers holding
/// ports pass `ports.rate_limiter.is_some()`; the build-time gate and
/// `fz doctor` pass [`rate_limiter_effective`], the runtime's own answer.
///
/// The signer leg is keyed the same way on `signer_ready` (issue #478):
/// the runtimes advertise [`Port::Signer`] yet leave `ports.signer ==
/// None` when the harness configuration fails to parse. Callers holding
/// ports pass `ports.signer.is_some()`; the build-time gate passes
/// [`signer_effective`].
///
/// [`ConfigError`]: crate::config::ConfigError
#[must_use]
pub fn production_readiness(
    env: VentureEnv,
    guards: &WriteGuards,
    runtime: Option<&Arc<dyn Runtime>>,
    rate_limiter_ready: bool,
    signer_ready: bool,
    allow_no_captcha: Option<&str>,
    allow_unlimited: Option<&str>,
) -> Vec<String> {
    if env != VentureEnv::Production {
        return Vec::new();
    }
    let mut errors = Vec::new();
    if guards.needs_captcha()
        && !captcha_effective(runtime)
        && stated_reason(allow_no_captcha).is_none()
    {
        errors.push(format!(
            "production venture has captcha-guarded public writes from [{}] but the Captcha \
             port is not effectively configured: provide it on the runtime with a bound \
             adapter (Turnstile needs its secret and expected hostname) — `fz doctor \
             --allow-no-captcha <reason>` overrides this check for previews only, and \
             {ALLOW_UNPROTECTED_WRITES} records the acceptance in a serving deployment",
            guards.captcha_modules.join(", ")
        ));
    }
    if guards.needs_signer() && !signer_ready {
        errors.push(format!(
            "production venture has signed-link public writes from [{}] but the Signer port \
             is not provided — the magic links, challenges and unsubscribe links those \
             routes verify cannot be issued or checked without one (issue #143)",
            guards.signed_link_modules.join(", ")
        ));
    }
    if guards.needs_payments() && !payments_effective(runtime) {
        errors.push(format!(
            "production venture has signature-guarded routes from [{}] that verify through \
             Payments but the Payments port is not provided — those webhook deliveries cannot \
             be verified (see the Inbox dedup ledger and the STRIPE_WEBHOOK_SECRET doctor \
             rule; modules verifying with the webhook_signature HMAC scheme instead are \
             gated on their own secret key, not this port)",
            guards.payments_signature_modules.join(", ")
        ));
    }
    if guards.needs_rate_limiter()
        && !rate_limiter_ready
        && stated_reason(allow_unlimited).is_none()
    {
        errors.push(format!(
            "production venture takes public writes or admin routes but the RateLimiter port \
             is not resolved: admin bearer routes have no brute-force backstop behind the \
             limiter (the fail-closed rule the sidecar forward runs) and every public write \
             runs without a budget — resolve the binding so the runtime actually hands over \
             a limiter, or set {ALLOW_UNLIMITED_PUBLIC_ROUTES} to a reason to serve \
             unlimited (issue #437)"
        ));
    }
    errors
}

/// The shared CAPTCHA gate for `HumanForm` handlers (issue #133): the
/// single place a module asks "is this form submission a human?".
///
/// Fail-closed rules, in order:
///
/// - the port is present: the token must exist and verify — any
///   non-`ok` verdict or transport error is a `captcha-failed` problem;
/// - the port is absent in **production**: `captcha-failed` as well.
///   `Harness::build` refuses that composition, so reaching this branch
///   means a runtime lied about its binding — refuse rather than wave
///   the request through. **Unless** `accepted_unprotected`: an operator
///   has recorded that this deployment serves without the port
///   (`HARNESS_ALLOW_UNPROTECTED_WRITES`, issue #143), the boot gate
///   honoured that and served, and refusing here would be the same
///   outage the acceptance exists to avoid, with a different status
///   code. The record is the accountability, not this branch;
/// - the port is absent in development/staging: allow, so a staging
///   deploy can drive the form without a live Turnstile.
///
/// # Errors
///
/// A `captcha-failed` problem when the submission is not proven human.
pub async fn verify_human_form(
    captcha: Option<&Arc<dyn Captcha>>,
    env: VentureEnv,
    accepted_unprotected: bool,
    token: Option<&str>,
    remote_ip: Option<&str>,
    instance: &str,
) -> Result<(), Problem> {
    let refused = || Problem::new(&SLUGS.captcha_failed).instance(instance);
    match captcha {
        Some(captcha) => {
            let Some(token) = token else {
                return Err(refused());
            };
            match captcha.verify(token, remote_ip).await {
                Ok(verdict) if verdict.ok => Ok(()),
                _ => Err(refused()),
            }
        }
        // No port, in production, with nobody having accepted that: the
        // composition `Harness::build` refuses is somehow serving, so
        // refuse the request rather than wave it through.
        None if env == VentureEnv::Production && !accepted_unprotected => Err(refused()),
        None => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Migrations;
    use crate::ports::{CaptchaError, Verdict};
    use crate::surface::Action;
    use async_trait::async_trait;

    struct StubCaptcha {
        ok: bool,
        transport_error: bool,
    }

    #[async_trait]
    impl Captcha for StubCaptcha {
        async fn verify(
            &self,
            _token: &str,
            _remote_ip: Option<&str>,
        ) -> Result<Verdict, CaptchaError> {
            if self.transport_error {
                return Err(CaptchaError::Transport("down".to_owned()));
            }
            Ok(Verdict {
                ok: self.ok,
                reason: None,
            })
        }
    }

    fn port(ok: bool, transport_error: bool) -> Arc<dyn Captcha> {
        Arc::new(StubCaptcha {
            ok,
            transport_error,
        })
    }

    #[pollster::test]
    async fn verified_tokens_pass_in_every_environment() {
        for env in [
            VentureEnv::Development,
            VentureEnv::Staging,
            VentureEnv::Production,
        ] {
            verify_human_form(
                Some(&port(true, false)),
                env,
                false,
                Some("token"),
                Some("203.0.113.7"),
                "request-1",
            )
            .await
            .expect("a verified token passes");
        }
    }

    #[pollster::test]
    async fn refused_missing_or_unreachable_verifications_fail_closed() {
        let good = port(true, false);
        let refused = port(false, false);
        let unreachable = port(true, true);
        for env in [VentureEnv::Development, VentureEnv::Production] {
            assert!(
                verify_human_form(Some(&refused), env, false, Some("t"), None, "r")
                    .await
                    .is_err()
            );
            assert!(
                verify_human_form(Some(&unreachable), env, false, Some("t"), None, "r")
                    .await
                    .is_err()
            );
            assert!(
                verify_human_form(Some(&good), env, false, None, None, "r")
                    .await
                    .is_err()
            );
        }
    }

    #[pollster::test]
    async fn absent_port_refuses_production_and_allows_lower_envs() {
        assert!(
            verify_human_form(None, VentureEnv::Production, false, Some("t"), None, "r")
                .await
                .is_err()
        );
        for env in [VentureEnv::Development, VentureEnv::Staging] {
            assert!(
                verify_human_form(None, env, false, Some("t"), None, "r")
                    .await
                    .is_ok()
            );
        }
    }

    struct Guarded {
        name: &'static str,
        surface: Surface,
        public_writes: bool,
        public_write_policy: RoutePolicy,
        verification: SignatureVerification,
    }

    impl Module for Guarded {
        fn name(&self) -> &'static str {
            self.name
        }
        fn version(&self) -> &'static str {
            "0.0.0-test"
        }
        fn requires(&self) -> &'static [Port] {
            &[]
        }
        fn public_writes(&self) -> bool {
            self.public_writes
        }
        fn public_write_policy(&self) -> RoutePolicy {
            self.public_write_policy
        }
        fn signature_verification(&self) -> SignatureVerification {
            self.verification
        }
        fn migrations(&self) -> Migrations {
            Migrations::default()
        }
        fn validate_config(
            &self,
            _: &dyn crate::config::Config,
        ) -> Result<(), crate::config::ConfigError> {
            Ok(())
        }
        fn surface(&self) -> Surface {
            self.surface.clone()
        }
        fn router(&self, _: crate::ModuleContext) -> axum::Router {
            axum::Router::new()
        }
    }

    fn module(name: &'static str, actions: Vec<Action>, public_writes: bool) -> Arc<dyn Module> {
        Arc::new(Guarded {
            name,
            surface: Surface {
                actions,
                views: vec![],
            },
            public_writes,
            public_write_policy: RoutePolicy::HumanForm,
            verification: SignatureVerification::Payments,
        })
    }

    /// A surface-less public writer that declares what really guards it.
    fn declaring(name: &'static str, policy: RoutePolicy) -> Arc<dyn Module> {
        Arc::new(Guarded {
            name,
            surface: Surface {
                actions: vec![],
                views: vec![],
            },
            public_writes: true,
            public_write_policy: policy,
            verification: SignatureVerification::Payments,
        })
    }

    #[test]
    fn human_form_action_requires_captcha() {
        let guards = WriteGuards::collect(&[module(
            "forms",
            vec![Action::post("join", "/").policy(RoutePolicy::HumanForm)],
            false,
        )]);
        assert_eq!(guards.captcha_modules, vec!["forms".to_owned()]);
        assert!(!guards.needs_payments());
    }

    #[test]
    fn signature_action_never_requires_captcha() {
        // The old bug: a webhook counted as "protected", so a captcha
        // config problem passed unnoticed AND the widget rendered on the
        // webhook. A Signature-only module must ask for Payments only.
        let guards = WriteGuards::collect(&[module(
            "billing",
            vec![Action::post("webhook", "/webhook").policy(RoutePolicy::Signature)],
            true, // even with the legacy flag set, the declared policy wins
        )]);
        assert!(guards.captcha_modules.is_empty());
        assert_eq!(guards.signature_modules, vec!["billing".to_owned()]);
    }

    #[test]
    fn undeclared_public_writer_falls_back_to_captcha() {
        let guards = WriteGuards::collect(&[module("auth", Vec::new(), true)]);
        assert_eq!(guards.captcha_modules, vec!["auth".to_owned()]);
    }

    #[test]
    fn legacy_captcha_flag_alias_still_guards() {
        // Pre-#133 declaration shapes — a bare `captcha: true` without a
        // policy — must still pull the module into the captcha gate.
        let mut action = Action::post("join", "/");
        action.captcha = true;
        let guards = WriteGuards::collect(&[module("forms", vec![action], false)]);
        assert_eq!(guards.captcha_modules, vec!["forms".to_owned()]);
    }

    #[test]
    fn guarded_surface_does_not_need_the_fallback() {
        // A module with declared policies is read as declared: `public_writes`
        // adds nothing on top (a form writer declares HumanForm; the
        // fallback exists for modules that predate surfaces).
        let guards = WriteGuards::collect(&[module(
            "waitlist",
            vec![
                Action::post("join", "/").captcha(),
                Action::post("webhook", "/webhook").policy(RoutePolicy::Signature),
            ],
            true,
        )]);
        assert_eq!(guards.captcha_modules, vec!["waitlist".to_owned()]);
        assert_eq!(guards.signature_modules, vec!["waitlist".to_owned()]);
    }

    #[test]
    fn development_venture_needs_nothing() {
        let guards = WriteGuards::collect(&[module("forms", Vec::new(), true)]);
        for env in [VentureEnv::Development, VentureEnv::Staging] {
            assert!(
                production_readiness(env, &guards, None, true, false, None, None).is_empty(),
                "{env:?} must not gate"
            );
        }
    }

    #[test]
    fn production_without_runtime_refuses_captcha_writes() {
        let guards = WriteGuards::collect(&[module(
            "forms",
            vec![Action::post("join", "/").captcha()],
            false,
        )]);
        // The limiter leg is held aside (`rate_limiter_ready = true`) so
        // this test stays about the captcha leg; #437's own tests are
        // below.
        let errors = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            true,
            false,
            None,
            None,
        );
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("forms"));
        assert!(errors[0].contains("Captcha"));
        // The override exists for `fz doctor` previews only.
        assert!(
            production_readiness(
                VentureEnv::Production,
                &guards,
                None,
                true,
                false,
                Some("preview"),
                None
            )
            .is_empty()
        );
        // And it is the *reason* that overrides, not the flag. `fz
        // doctor --allow-no-captcha ""` hands this `Some("")`, and an
        // override with nothing to answer for is the silent default
        // `ALLOW_UNPROTECTED_WRITES` already refuses to be — its
        // `unprotected_writes_override` trims and drops an empty one.
        // Two ways to the same waiver, and only one of them asked for a
        // reason.
        for nothing in ["", "   ", "\t\n"] {
            assert_eq!(
                production_readiness(
                    VentureEnv::Production,
                    &guards,
                    None,
                    true,
                    false,
                    Some(nothing),
                    None
                )
                .len(),
                1,
                "an empty reason waived the captcha gate: {nothing:?}"
            );
        }
    }

    #[test]
    fn production_signature_without_payments_refuses() {
        let guards = WriteGuards::collect(&[module(
            "billing",
            vec![Action::post("webhook", "/webhook").policy(RoutePolicy::Signature)],
            false,
        )]);
        let errors = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            true,
            false,
            None,
            None,
        );
        assert_eq!(errors.len(), 1);
        assert!(errors[0].contains("billing"));
        assert!(errors[0].contains("Payments"));
        // No override for the payments leg — webhooks cannot be "previewed"
        // unverified without shipping unsigned money events.
        assert_eq!(
            production_readiness(
                VentureEnv::Production,
                &guards,
                None,
                true,
                false,
                Some("preview"),
                None
            )
            .len(),
            1
        );
    }

    // ------------------------------------------------ issue #533

    use crate::config::MapConfig;

    /// A webhook receiver verifying with the core HMAC scheme, holding its
    /// secret under `{MODULE}_WEBHOOK_SECRET`.
    fn hmac_module(name: &'static str) -> Arc<dyn Module> {
        Arc::new(Guarded {
            name,
            surface: Surface {
                actions: vec![Action::post("webhook", "/webhook").policy(RoutePolicy::Signature)],
                views: vec![],
            },
            public_writes: false,
            public_write_policy: RoutePolicy::HumanForm,
            verification: SignatureVerification::Hmac {
                secret: "WEBHOOK_SECRET",
            },
        })
    }

    #[test]
    fn an_hmac_signature_writer_needs_no_payments_and_names_its_secret_key() {
        let guards = WriteGuards::collect(&[hmac_module("pos")]);
        assert_eq!(guards.signature_modules, ["pos"]);
        assert!(!guards.needs_payments());
        assert_eq!(
            guards.hmac_signature_secrets(),
            vec![("pos".to_owned(), "POS_WEBHOOK_SECRET".to_owned())],
            "the full key is composed through ModuleConfig's prefix rule"
        );
    }

    #[test]
    fn the_webhook_secret_gate_is_production_only() {
        let guards = WriteGuards::collect(&[hmac_module("pos")]);
        // No runtime at all — no Payments port anywhere — and production is
        // clean once the secret is set.
        let set = MapConfig::from_pairs([("POS_WEBHOOK_SECRET", "whsec-test-dummy")]);
        assert!(
            production_readiness(
                VentureEnv::Production,
                &guards,
                None,
                true,
                false,
                None,
                None
            )
            .is_empty()
        );
        assert!(webhook_secret_readiness(VentureEnv::Production, &guards, &set).is_empty());
        // Missing or blank refuses in production, naming the module and the
        // key; staging demands nothing (the handler refuses every delivery
        // per request anyway).
        for config in [
            MapConfig::default(),
            MapConfig::from_pairs([("POS_WEBHOOK_SECRET", "   ")]),
        ] {
            let errors = webhook_secret_readiness(VentureEnv::Production, &guards, &config);
            assert_eq!(errors.len(), 1, "{errors:?}");
            assert!(
                errors[0].contains("pos") && errors[0].contains("POS_WEBHOOK_SECRET"),
                "{}",
                errors[0]
            );
        }
        assert!(
            webhook_secret_readiness(VentureEnv::Staging, &guards, &MapConfig::default())
                .is_empty()
        );
    }

    #[test]
    fn a_mixed_venture_gates_payments_only_for_the_module_that_names_it() {
        // A sidecar document cannot name a verifier, so it keeps the
        // pre-#533 behaviour: the Payments gate.
        let surface = Surface {
            actions: vec![Action::post("webhook", "/webhook").policy(RoutePolicy::Signature)],
            views: vec![],
        };
        assert!(WriteGuards::from_surface("remote", &surface).needs_payments());
        // A mixed venture still demands Payments for exactly the module
        // that verifies through it.
        let guards = WriteGuards::collect(&[
            hmac_module("pos"),
            declaring("billing", RoutePolicy::Signature),
        ]);
        assert!(guards.needs_payments());
        let errors = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            true,
            false,
            None,
            None,
        );
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].contains("billing") && !errors[0].contains("pos"),
            "{}",
            errors[0]
        );
    }

    // ------------------------------------------------ issue #143

    #[test]
    fn the_deployment_environment_is_the_stricter_of_the_two() {
        // The bug: `ventures/cratefield-waitlist` ships ENV="production"
        // and never calls `.env()`, so every production rule read the
        // compiled `Development` and did not apply in production.
        let deployed = MapConfig::from_pairs([("ENV", "production")]);
        assert_eq!(
            deployed_env(VentureEnv::Development, &deployed),
            VentureEnv::Production,
        );
        // And the other way: a binding must not be able to switch the
        // protections off for a venture compiled as production.
        let downgrade = MapConfig::from_pairs([("ENV", "development")]);
        assert_eq!(
            deployed_env(VentureEnv::Production, &downgrade),
            VentureEnv::Production,
        );
        // No binding at all leaves the compiled answer standing.
        assert_eq!(
            deployed_env(VentureEnv::Staging, &MapConfig::default()),
            VentureEnv::Staging,
        );
        // Agreement is not a disagreement.
        assert!(env_disagreement(VentureEnv::Production, VentureEnv::Production).is_none());
        let note = env_disagreement(VentureEnv::Development, VentureEnv::Production)
            .expect("a compiled-vs-deployed mismatch is reported");
        assert!(note.contains("ENV=production"), "{note}");
        // The literal is split across lines; it renders as one sentence (issue #477).
        assert!(!note.contains("  "), "{note}");
        assert!(
            note.contains("compiled with VentureEnv::Development: the production readiness gate"),
            "{note}"
        );
    }

    #[test]
    fn a_surface_less_writer_declares_what_actually_guards_it() {
        // Saying nothing is unchanged: still the conservative CAPTCHA
        // fallback, so no existing module moves.
        let guards = WriteGuards::collect(&[module("legacy", vec![], true)]);
        assert_eq!(guards.captcha_modules, ["legacy"]);
        assert!(!guards.needs_signer());

        // A passkey ceremony or an OAuth callback is proved by an artifact
        // this service issued, and will never render a widget.
        let guards = WriteGuards::collect(&[declaring("passkeys", RoutePolicy::SignedLink)]);
        assert!(
            guards.captcha_modules.is_empty(),
            "a signed-link writer must not demand a captcha it never renders"
        );
        assert_eq!(guards.signed_link_modules, ["passkeys"]);
        assert!(guards.needs_signer());
    }

    #[test]
    fn a_signed_link_writer_still_has_a_production_requirement_of_its_own() {
        // Not an exemption: without a Signer there is nothing to issue or
        // verify the artifact with, so production still refuses.
        let guards = WriteGuards::collect(&[declaring("passkeys", RoutePolicy::SignedLink)]);
        let errors = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            true,
            false,
            None,
            None,
        );
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("signed-link"), "{}", errors[0]);
        assert!(errors[0].contains("passkeys"), "{}", errors[0]);

        // And nothing is demanded outside production.
        assert!(
            production_readiness(VentureEnv::Staging, &guards, None, true, false, None, None)
                .is_empty()
        );
    }

    #[test]
    fn a_production_venture_needs_a_resolved_signer() {
        // Issue #478: the runtime advertises the Signer port, but a
        // harness configuration that fails to parse (a bad `ENV`, a short
        // `ADMIN_TOKEN`) leaves `ports.signer == None`. Advertised is not
        // resolved, so the caller's answer decides the leg.
        struct Advertises;
        impl Runtime for Advertises {
            fn provides(&self) -> Vec<Port> {
                vec![Port::Signer]
            }
        }
        let runtime: Arc<dyn Runtime> = Arc::new(Advertises);
        let guards = WriteGuards::collect(&[declaring("passkeys", RoutePolicy::SignedLink)]);
        let check = |env, signer_ready| {
            production_readiness(env, &guards, Some(&runtime), true, signer_ready, None, None)
        };

        let errors = check(VentureEnv::Production, false);
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("Signer"), "{}", errors[0]);
        // The literal is split across lines; it renders as one sentence, the
        // same fix #511 made to the ENV warning (#512 made this reachable at boot).
        assert!(!errors[0].contains("  "), "{}", errors[0]);
        assert!(
            errors[0].contains("but the Signer port is not provided"),
            "{}",
            errors[0]
        );
        assert!(check(VentureEnv::Production, true).is_empty());
        assert!(check(VentureEnv::Development, false).is_empty());
    }

    #[test]
    fn a_declared_policy_on_an_action_still_wins_over_the_fallback() {
        // The fallback applies only when the surface declares nothing —
        // a module with a guarded action is untouched by #143.
        let guards = WriteGuards::collect(&[Arc::new(Guarded {
            name: "mixed",
            surface: Surface {
                actions: vec![Action::post("join", "/join").policy(RoutePolicy::HumanForm)],
                views: vec![],
            },
            public_writes: true,
            public_write_policy: RoutePolicy::SignedLink,
            verification: SignatureVerification::Payments,
        })]);
        assert_eq!(guards.captcha_modules, ["mixed"]);
        assert!(
            guards.signed_link_modules.is_empty(),
            "the module-level fallback must not override a declared action"
        );
    }

    // ------------------------------------------------ issue #437

    #[test]
    fn admin_and_public_writes_are_recorded_on_the_guards() {
        // An admin action alone is enough: the bearer token is guessed,
        // not submitted, so the budget question is not a corollary of the
        // public-write one.
        let guards = WriteGuards::collect(&[module(
            "exports",
            vec![Action::post("export", "/admin/export").audience(Audience::Admin)],
            false,
        )]);
        assert!(guards.has_admin_routes);
        assert!(!guards.has_public_writes);
        assert!(guards.needs_rate_limiter());

        // The path half of the predicate, for an action whose audience
        // was never declared.
        let guards = WriteGuards::collect(&[module(
            "landing",
            vec![Action::get("console", "/admin/console")],
            false,
        )]);
        assert!(guards.has_admin_routes);

        // The module-level fallback flag counts as a public write, the
        // way the captcha fallback does.
        let guards = WriteGuards::collect(&[module("legacy", Vec::new(), true)]);
        assert!(guards.has_public_writes);
        assert!(!guards.has_admin_routes);

        // And a webhook is an unauthenticated endpoint: it counts for the
        // limiter leg even though it asks nothing of the captcha one.
        let guards = WriteGuards::collect(&[module(
            "billing",
            vec![Action::post("webhook", "/webhook").policy(RoutePolicy::Signature)],
            false,
        )]);
        assert!(guards.has_public_writes);
    }

    #[test]
    fn a_production_venture_needs_a_resolved_rate_limiter() {
        let guards = WriteGuards::collect(&[module(
            "forms",
            vec![Action::post("join", "/").captcha()],
            false,
        )]);

        // Advertised is not resolved: the Cloudflare runtime reports the
        // port from a configured binding name and still hands over `None`
        // when the binding fails to resolve. The caller says which
        // happened, and the captcha waiver next door does not reach this
        // leg.
        let unlimited = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            false,
            false,
            Some("preview"),
            None,
        );
        assert_eq!(unlimited.len(), 1, "{unlimited:?}");
        assert!(unlimited[0].contains("RateLimiter"), "{}", unlimited[0]);
        assert!(
            unlimited[0].contains(ALLOW_UNLIMITED_PUBLIC_ROUTES),
            "{}",
            unlimited[0]
        );

        // Resolved: the leg passes.
        assert!(
            production_readiness(
                VentureEnv::Production,
                &guards,
                None,
                true,
                false,
                Some("preview"),
                None
            )
            .is_empty()
        );

        // Waived with a reason it passes; waived with a blank one it does
        // not — the same "a blank reason is not an acceptance" rule the
        // captcha override runs on.
        assert!(
            production_readiness(
                VentureEnv::Production,
                &guards,
                None,
                false,
                false,
                Some("preview"),
                Some("issue #437: between pivots"),
            )
            .is_empty()
        );
        for nothing in ["", "   "] {
            assert_eq!(
                production_readiness(
                    VentureEnv::Production,
                    &guards,
                    None,
                    false,
                    false,
                    Some("preview"),
                    Some(nothing),
                )
                .len(),
                1,
                "an empty reason waived the limiter gate: {nothing:?}"
            );
        }
    }

    #[test]
    fn a_module_with_only_admin_routes_still_needs_the_limiter() {
        let guards = WriteGuards::collect(&[module(
            "exports",
            vec![Action::post("export", "/admin/export").audience(Audience::Admin)],
            false,
        )]);
        assert!(guards.captcha_modules.is_empty());
        let errors = production_readiness(
            VentureEnv::Production,
            &guards,
            None,
            false,
            false,
            None,
            None,
        );
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("RateLimiter"), "{}", errors[0]);
        assert!(
            errors[0].contains(ALLOW_UNLIMITED_PUBLIC_ROUTES),
            "{}",
            errors[0]
        );
    }

    // ------------------------------------------------ issue #532

    #[test]
    fn an_api_key_policy_serializes_as_api_key_and_guards() {
        assert_eq!(
            serde_json::to_string(&RoutePolicy::ApiKey).expect("serializes"),
            "\"api-key\""
        );
        let policy: RoutePolicy = serde_json::from_str("\"api-key\"").expect("deserializes");
        assert_eq!(policy, RoutePolicy::ApiKey);
        assert!(policy.is_guarded());
    }

    #[test]
    fn an_api_key_writer_demands_no_captcha_and_no_port() {
        // A declared api-key action is read as declared: no captcha (a
        // developer machine cannot fill one), no Signer, no Payments —
        // and not the public-write leg either, because its budget is the
        // per-key limiter hook, not a boot gate.
        let guards = WriteGuards::collect(&[module(
            "devapi",
            vec![Action::post("sync", "/sync").policy(RoutePolicy::ApiKey)],
            false,
        )]);
        assert!(guards.captcha_modules.is_empty());
        assert!(guards.signature_modules.is_empty());
        assert!(guards.signed_link_modules.is_empty());
        assert!(!guards.has_public_writes);
        assert!(!guards.needs_rate_limiter());

        // The surface-less fallback is the same: guarded, never pulled
        // into the captcha gate.
        let guards = WriteGuards::collect(&[declaring("devapi", RoutePolicy::ApiKey)]);
        assert!(
            guards.captcha_modules.is_empty(),
            "an api-key writer must not demand a captcha it never renders"
        );
        assert!(!guards.needs_signer());
        assert!(!guards.needs_payments());
    }
}