boatramp-node 0.2.2

Node assembly for boatramp: the parsed config model (and, incrementally, the config-to-running-node assembly) that the serve binary and library embedders share.
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
//! Local configuration files (RON).
//!
//! Two distinct files, split by audience:
//!
//! - **`project.cfg`** — one per project folder, read by the client commands
//!   (`sync`, `build`, `bundle`, `validate`): where/how to publish, the optional
//!   build/bundle steps, and the deploy-scoped `routing` config that is folded
//!   into the immutable deployment manifest. See [`ProjectConfig`].
//! - **`boatramp.cfg`** — the server daemon config, read by `serve`:
//!   `serve` / `handlers` / `cluster`. See [`ServerConfig`].
//!
//! Both are RON; a missing file yields the default config.

use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};

use boatramp_core::config::DeployConfig;
use serde::Deserialize;

/// RON parse options shared by both loaders: `implicit_some` lets optional fields
/// be written as bare values (`server: "..."`, not `Some("...")`). `pub` so the
/// binary (which re-exports this module) can parse a manifest with the same
/// options after the module moved into this crate.
pub fn ron_options() -> ron::Options {
    ron::Options::default().with_default_extension(ron::extensions::Extensions::IMPLICIT_SOME)
}

/// A failure loading or parsing a local config file (`project.cfg` / `boatramp.cfg`).
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// Wraps an underlying error with the file path it came from.
    #[error("{path}: {source}")]
    File {
        path: String,
        #[source]
        source: Box<Self>,
    },
    /// The RON document failed to parse.
    #[error("invalid config syntax: {0}")]
    Ron(#[from] ron::error::SpannedError),
    /// The `routing` section failed its compile-check.
    #[error("routing: {0}")]
    Routing(#[from] boatramp_core::ConfigError),
    /// Reading the file failed (other than not-found, which yields defaults).
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

/// Project configuration, loaded from `project.cfg` (RON) in the project folder.
///
/// Read by the client commands (`sync`, `build`, `bundle`, `validate`).
/// Everything is optional; a missing file is the default.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
    /// Where and how to publish this project.
    pub publish: PublishConfig,
    /// Optional build step run before `sync`.
    pub build: Option<BuildConfig>,
    /// Optional embedded-bundler step (`bundler` feature).
    pub bundle: Option<BundleConfig>,
    /// Deploy-scoped routing/handlers config. Folded into the deployment
    /// manifest at `sync` (so it is atomic with the content and rolls back with
    /// it). The bulk of a project's config — redirects, rewrites, headers,
    /// handlers, consumers, crons, streams.
    pub routing: DeployConfig,
}

impl ProjectConfig {
    /// Parse a `project.cfg` document (RON). The `routing` section is
    /// compile-checked (route patterns, cron schedules, imports) so a bad config
    /// fails fast.
    pub fn parse(text: &str) -> Result<Self, ConfigError> {
        let config: Self = ron_options().from_str(text)?;
        config.routing.compile_check()?;
        Ok(config)
    }

    /// Load from `path` (RON). A missing file yields the default config.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        match std::fs::read_to_string(path) {
            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
                path: path.display().to_string(),
                source: Box::new(err),
            }),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(err) => Err(err.into()),
        }
    }
}

/// Server daemon configuration, loaded from `boatramp.cfg` (RON). Read by
/// `boatramp serve`; flags/env override the `serve` values.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct ServerConfig {
    /// Server defaults for `serve` (flag/env override these).
    pub serve: Option<ServeConfig>,
    /// Server-side handler runtime config (which backend serves each binding),
    /// consumed only with the `handlers` feature.
    pub handlers: Option<HandlersConfig>,
    /// Self-hosted cluster mode (consumed only with the `cluster` feature).
    pub cluster: Option<ClusterConfig>,
    /// Opt-in **compute** backends. Present ⇒ this node
    /// runs compute workloads via the backends it can offer; absent ⇒ no compute
    /// (the reconcile loop stays a no-op).
    pub compute: Option<ComputeConfig>,
    /// Operator security posture (the hardening knobs): a profile
    /// preset + overrides, resolved at startup. Absent ⇒ the strict
    /// `multi-tenant` default. Operator-only — never part of site config.
    pub security: Option<boatramp_core::security::SecurityConfig>,
    /// Secrets-at-rest envelope. Absent ⇒ private
    /// keys stored cleartext in the (replicated) control plane.
    pub secrets: Option<SecretsConfig>,
}

/// `secrets` section — envelope encryption for private keys at rest.
#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SecretsConfig {
    /// Backend: `"local"` (machine-local AES-256-GCM KEK) or `"vault"` (Vault
    /// Transit). Empty/other ⇒ no wrapping. In a cluster a local KEK must be the
    /// **same file on every node** (wrapped certs replicate); Vault avoids that.
    pub envelope: String,
    /// Local-KEK key file (`envelope = "local"`). Default
    /// `<data-dir>/secrets/kek`. Auto-generated `0600` if absent.
    pub kek_file: Option<PathBuf>,
    /// Vault Transit config (`envelope = "vault"`).
    pub vault: Option<VaultSecretsConfig>,
}

/// Vault Transit settings for `envelope = "vault"`. The token is read from the
/// environment (`token_env`), never stored in the config file.
#[cfg_attr(not(all(feature = "cluster", feature = "acme-dns")), allow(dead_code))]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VaultSecretsConfig {
    /// Vault address, e.g. `https://vault:8200`.
    pub addr: String,
    /// Transit key name to wrap under.
    pub key: String,
    /// Environment variable holding the Vault token (default `VAULT_TOKEN`).
    #[serde(default = "default_vault_token_env")]
    pub token_env: String,
}

fn default_vault_token_env() -> String {
    "VAULT_TOKEN".to_string()
}

impl ServerConfig {
    /// Parse a `boatramp.cfg` document (RON).
    pub fn parse(text: &str) -> Result<Self, ConfigError> {
        Ok(ron_options().from_str(text)?)
    }

    /// Load from `path` (RON). A missing file yields the default config.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        match std::fs::read_to_string(path) {
            Ok(contents) => Self::parse(&contents).map_err(|err| ConfigError::File {
                path: path.display().to_string(),
                source: Box::new(err),
            }),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(err) => Err(err.into()),
        }
    }
}

/// `compute` section — opt-in compute backends. Present
/// ⇒ `serve` registers the backends this node can offer and advertises them to
/// the scheduler; backends are capability-detected (container on Linux, remote
/// docker when a daemon is reachable, VMM when `/dev/kvm` exists).
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ComputeConfig {
    /// Bridge the container veths / VM taps attach to (default `br-boatramp`).
    pub bridge: String,
    /// Guest IP subnet (default `10.0.0.0/24`).
    pub subnet: String,
    /// vCPUs this node advertises as schedulable (`0` ⇒ detect from the host).
    pub vcpus: u32,
    /// Memory (MiB) this node advertises as schedulable (`0` ⇒ a 1 GiB default).
    pub mem_mib: u32,
    /// **Static** kernel-signing public keys (`"<alg>:<hex>"`) — the trust anchor
    /// for the posture-scaled kernel bar. Under `multi-tenant`, a dynamically-
    /// selected default kernel must carry a signature verifying against one of
    /// these. Host-access-gated (never in the KV tier); changing it needs a
    /// restart. Empty ⇒ no kernel may be signed-verified (strict posture then
    /// accepts none).
    pub kernel_signing_pubkeys: Vec<String>,
    /// **Static** allow-list of kernel content hashes (sha256 hex) a dynamic
    /// default may select under `multi-tenant`. Host-access-gated. Empty ⇒ no
    /// kernel is allow-listed.
    pub kernel_allowed_hashes: Vec<String>,
    /// This node's **region** tag (FA-8). Advertised on the compute `Node` so a
    /// gateway routing to a `compute:`-backed workload with `--lb nearest` sends
    /// each request to the nearest replica by its node's region — no manual
    /// `--region` map. `None` ⇒ region-agnostic.
    pub region: Option<String>,
    /// How the remote-Docker backend reports a workload's reachable endpoint.
    /// `published` (default) publishes the container port on `127.0.0.1:<ephemeral>`
    /// so a host-native `serve` reaches it on any daemon (incl. Docker Desktop /
    /// macOS, where the bridge IP is not host-routable); `bridge` routes to the
    /// container bridge IP directly (only when `serve` shares the daemon's network).
    pub docker_endpoint: boatramp_docker::DockerEndpoint,
    /// How the remote-Docker backend backs a workload's persistent volumes.
    /// `named` (default) attaches a daemon-managed `docker volume` by name (portable
    /// across daemons + Docker Desktop / macOS); `bind` bind-mounts a host directory
    /// under `<data_dir>/compute/volumes/<name>` (local daemon only).
    pub docker_volume_mode: boatramp_docker::DockerVolumeMode,
    /// Guest-reachable base URL of the compute **sql-shim** (PLAN-compute-bindings) —
    /// e.g. `http://10.0.0.1:8081` (the compute bridge gateway) or the docker bridge
    /// gateway. Set ⇒ a workload's `--bind sql` reaches the managed database through a
    /// listener bound on `0.0.0.0:<port>`. `None` (default) ⇒ compute sql bindings off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(not(feature = "handlers"), allow(dead_code))]
    pub sql_shim_url: Option<String>,
}

/// The built-in **boatramp kernel-signing public key** (`es256:…`), whose private
/// half lives as the `KERNEL_SIGNING_KEY` Actions secret in
/// [`BoatRamp/boatramp-vmlinux`](https://github.com/BoatRamp/boatramp-vmlinux).
/// Shipped as a default trust anchor so the first-party signed `boatramp-vmlinux`
/// verifies out of the box under the strict posture. An operator can replace
/// `kernel_signing_pubkeys` to trust only their own keys.
pub const BOATRAMP_KERNEL_SIGNING_PUBKEY: &str =
    "es256:02c4e4af2e9cba6ba6745c513f193622e6674a8b2d0187ebea5612f5b46a7eade4";

impl Default for ComputeConfig {
    fn default() -> Self {
        Self {
            bridge: "br-boatramp".to_string(),
            subnet: "10.0.0.0/24".to_string(),
            vcpus: 0,
            mem_mib: 0,
            kernel_signing_pubkeys: vec![BOATRAMP_KERNEL_SIGNING_PUBKEY.to_string()],
            // Signed `boatramp-vmlinux` release kernels trusted under the strict
            // posture (content sha256), so a selected `compute.default_kernel`
            // clears the bar out of the box. Bump on each new signed release.
            kernel_allowed_hashes: vec![
                // v0.2.0 minimal Firecracker 6.1-config kernel: boots under the
                // firecracker-*binary* backend (ACPI device discovery) but NOT the
                // in-process embedded VMM. Kept trusted so operators on the currently
                // published release don't fail strict verification.
                "cf1e590a9e642be3667131ca35fbf390378a457d8908169d2a169608e299d974".to_string(),
                // Same kernel + CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y (flake `#vmlinux`),
                // so the embedded VMM binds its virtio-block root over the cmdline
                // transport. Reproducible build output (deterministic nix build,
                // verified on KVM); the next signed boatramp-vmlinux release — which
                // reuses this flake — publishes + signs it, gated by
                // `vmlinux-release-boot.yml`.
                "d0dc2098ab2a2a3c1bc72ab61dc85d9e464d798d7e55b6b80525db5ca2f00c5a".to_string(),
            ],
            region: None,
            docker_endpoint: boatramp_docker::DockerEndpoint::default(),
            docker_volume_mode: boatramp_docker::DockerVolumeMode::default(),
            sql_shim_url: None,
        }
    }
}

/// `cluster` section — self-hosted **cluster mode**. Parsed in
/// every build so config files stay portable; only *consumed* when the `cluster`
/// feature is compiled in (`boatramp serve --mode cluster`).
#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
#[derive(Debug, Clone, Deserialize)]
pub struct ClusterConfig {
    /// Address to bind this node's Raft **peer mesh** on (the `/raft/*` +
    /// `/stream/*` endpoints) — distinct from the public `serve.addr`.
    pub listen: SocketAddr,
    /// The cluster **root anchor set** — the `es256:`/`ed25519:`-tagged public
    /// keys that define this cluster's identity (a cluster *is* its root key).
    /// Every join/trust decision verifies against this set. Empty ⇒ falls back to
    /// `serve.auth_root_public_key` (the single-anchor default). A *set* enables
    /// make-before-break root rotation.
    #[serde(default)]
    pub root_pubkeys: Vec<String>,
    /// **Seeds** — control-plane addresses of existing cluster members
    /// (`host:port`), any of which can admit this node. Present ⇒ this node
    /// **joins** (redeems its `join_token`); absent + no durable state + explicit
    /// `--cluster-init` ⇒ it **founds**. There is no peer map: members are learned
    /// from the root-signed join response.
    #[serde(default)]
    pub seeds: Vec<String>,
    /// The single-use bearer **join token** used when `seeds` are set. Keeps the
    /// secret out of the file via a prefix: `env:VAR`, `path:/file`, or an inline
    /// literal. Usually supplied via `serve --cluster-join <ticket>` instead.
    #[serde(default)]
    pub join_token: Option<String>,
    /// Directory for this node's **durable** Raft log/state store (node-local;
    /// distinct from the replicated control plane). Default
    /// `<data-dir>/raft`.
    #[serde(default)]
    pub store_dir: Option<PathBuf>,
    /// Mesh identity + TLS settings. Absent ⇒ defaults (identity key
    /// auto-generated under `<data-dir>/mesh/identity.key`).
    #[serde(default)]
    pub mesh: Option<MeshConfig>,
}

/// `[cluster.mesh]` — mesh identity + TLS knobs.
#[cfg_attr(not(feature = "cluster"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct MeshConfig {
    /// Path to this node's Ed25519 identity key (PKCS#8 DER, `0600`,
    /// auto-generated). Default `<data-dir>/mesh/identity.key`.
    pub key_file: Option<PathBuf>,
    /// Automatic key-rotation cadence (e.g. `"30d"`); `None` = manual only.
    /// Consumed by the rotation loop.
    pub key_rotation: Option<String>,
    /// TTL for a single-use join token (e.g. `"1h"`).
    pub join_token_ttl: Option<String>,
    /// Gate mesh `client-write`s behind a control-plane **cluster-write
    /// capability**, so a trusted peer can't inject arbitrary
    /// control-plane writes on mesh trust alone. Requires the token root
    /// **private** key on every node (each mints + presents its own capability);
    /// default `false`.
    pub gate_client_writes: Option<bool>,
}

/// `handlers` section — server-side handler runtime config (read by `serve`).
/// Parsed in every build (so config files stay portable), but only *consumed*
/// when the `handlers` feature is compiled in.
#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct HandlersConfig {
    /// `handlers.bindings` — which backend serves each handler binding.
    pub bindings: BindingsConfig,
    /// Use the wasmtime **pooling** instance allocator: faster
    /// instantiation at the cost of a large up-front virtual-memory reservation.
    /// Off by default — opt in and benchmark for your workload.
    pub pooling: bool,
}

/// `handlers.bindings` — per-binding backend configuration. kv/blob reuse the
/// server's own KV/Storage backends (per-site prefixed); `sql` is the single
/// libsql backend, whose single-node-vs-cluster split is the only choice.
#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct BindingsConfig {
    /// `handlers.bindings.sql` — libsql settings. Absent ⇒ single-node,
    /// per-site embedded files under `<data-dir>/handlers-sql`.
    pub sql: Option<SqlBindingConfig>,
}

/// libsql settings for the handler `sql` binding — the single SQL backend. Each
/// site gets a real database boundary (an embedded file per site, or a sqld
/// namespace per site), never schema separation (which arbitrary guest SQL
/// escapes). Setting `url` switches from single-node to a shared sqld cluster;
/// everything else stays identical.
#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct SqlBindingConfig {
    /// Single-node: root directory for the per-site embedded database files
    /// (default `<data-dir>/handlers-sql`). Ignored when `url` is set.
    pub dir: Option<PathBuf>,
    /// Cluster: base sqld data URL (e.g. `http://sqld:8080`). When set, each
    /// site is a sqld namespace addressed as a subdomain of this URL; `admin_url`
    /// is then required.
    pub url: Option<String>,
    /// Cluster: sqld admin API base URL (e.g. `http://sqld:9090`) for creating
    /// per-site namespaces. Required when `url` is set.
    pub admin_url: Option<String>,
    /// Cluster: optional sqld **read-replica** data URL. When set, handlers'
    /// read-only `sql` transactions (`open-read-only`) route to this endpoint
    /// while writes stay on `url` (reads → replicas, writes → primary).
    /// Reads may lag (eventually consistent). Ignored in
    /// single-node mode (no `url`).
    pub replica_url: Option<String>,
    /// Name of the env var holding the sqld data auth token (optional; never
    /// the token itself in-file).
    pub token_env: Option<String>,
    /// Name of the env var holding the sqld admin API auth key (optional).
    pub admin_token_env: Option<String>,
    /// How preview deployments get their SQL database: `empty` (default — a
    /// fresh isolated db), `branch` (a consistent copy of the site's live db;
    /// single-node only), or `shared` (the site's live db). See
    /// `boatramp_core::sql::PreviewSqlMode`.
    pub preview_mode: Option<String>,
    /// Path to an idempotent SQL script run when an `empty` preview database is
    /// first opened (e.g. schema/seed). Ignored in `branch`/`shared` modes.
    pub preview_init: Option<PathBuf>,
    /// `handlers.bindings.sql.databases` — external **bring-your-own** databases,
    /// each opened by name via `sql.open("<name>")`. An operator-configured
    /// Postgres/MySQL whose *isolation is the operator's* (it's their database),
    /// so these bypass the per-site libsql boundary and are reachable by any
    /// handler/function granted the `sql` binding. Needs the `sql-postgres` /
    /// `sql-mysql` build feature for the engine. A name here shadows the same
    /// name on the managed libsql default.
    pub databases: BTreeMap<String, ExternalDatabaseConfig>,
}

/// One external (bring-your-own) SQL database for the handler `sql` binding. The
/// connection URL is a secret and is named indirectly (`url_env`), never written
/// in the config file.
#[cfg_attr(not(feature = "handlers"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ExternalDatabaseConfig {
    /// Engine: `postgres` (aliases `postgresql`/`pg`) or `mysql` (alias
    /// `mariadb`).
    pub kind: String,
    /// Name of the env var holding the connection URL (e.g.
    /// `postgres://user:pw@host/db`). Required.
    pub url_env: String,
    /// Optional env var holding a **read-replica** connection URL. When set,
    /// `open-read-only` transactions route there; writes stay on `url_env`.
    pub read_url_env: Option<String>,
    /// Maximum pooled connections (default 8).
    pub pool_max: Option<u32>,
    /// Open every transaction `READ ONLY` (the engine rejects writes) — for a
    /// database functions should only read.
    pub read_only: bool,
    /// Permit **preview** deployments to reach this database. Default `false`: a
    /// preview is refused, so it can never touch the operator's live external DB.
    pub allow_preview: bool,
    /// Connection/acquire timeout in seconds (default 10).
    pub connect_timeout_secs: Option<u64>,
}

/// The signing algorithm for a signer that can choose one (`Local`, `Vault`,
/// `Pkcs11`). ES256 is the portable default; the cloud KMS backends are ES256-only
/// and ignore this. Written as a RON enum: `alg: Es256` / `alg: Ed25519`.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
pub enum SignerAlg {
    /// ECDSA P-256 (COSE ES256) — the default.
    #[default]
    Es256,
    /// Ed25519 (COSE EdDSA).
    Ed25519,
}

impl SignerAlg {
    fn to_token_alg(self) -> boatramp_core::cose::TokenAlg {
        match self {
            Self::Es256 => boatramp_core::cose::TokenAlg::Es256,
            Self::Ed25519 => boatramp_core::cose::TokenAlg::Ed25519,
        }
    }
}

/// External token signer selector (`serve.signer`). Maps to
/// [`boatramp_server::signer::SignerConfig`]; secrets (tokens/PINs) are resolved
/// from the named env vars at startup, never stored in config. Written as a RON
/// enum — `signer: Vault(...)`, `signer: AwsKms(...)`, `signer: Pkcs11(...)`, ….
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum AuthSignerConfig {
    /// In-process key (`"<alg>:<hex>"`).
    Local {
        /// The private key spec, `"<alg>:<hex>"`.
        private_key: String,
    },
    /// HashiCorp Vault Transit key.
    Vault {
        /// Vault base address.
        address: String,
        /// The Transit key name.
        key: String,
        /// Env var holding the Vault token.
        token_env: String,
        /// The key algorithm.
        #[serde(default)]
        alg: SignerAlg,
    },
    /// AWS KMS asymmetric key (ES256).
    AwsKms {
        /// The KMS key id or ARN.
        key_id: String,
        /// Optional region override.
        #[serde(default)]
        region: Option<String>,
    },
    /// GCP Cloud KMS key version (ES256).
    GcpKms {
        /// The key-version resource name.
        key_version: String,
        /// Env var holding a GCP OAuth2 access token.
        access_token_env: String,
    },
    /// Azure Key Vault key (ES256).
    AzureKv {
        /// The vault base URL.
        vault_url: String,
        /// The key name.
        key: String,
        /// The key version.
        key_version: String,
        /// Env var holding an Azure AD access token.
        access_token_env: String,
    },
    /// PKCS#11 HSM key.
    Pkcs11 {
        /// Path to the PKCS#11 module.
        module: String,
        /// The token label.
        token_label: String,
        /// The key's `CKA_LABEL`.
        key_label: String,
        /// Env var holding the user PIN.
        pin_env: String,
        /// The key algorithm.
        #[serde(default)]
        alg: SignerAlg,
    },
}

impl AuthSignerConfig {
    /// Map the config-file form to the server's runtime [`SignerConfig`].
    pub fn to_signer_config(&self) -> boatramp_server::signer::SignerConfig {
        use boatramp_server::signer::SignerConfig;
        match self {
            Self::Local { private_key } => SignerConfig::Local {
                private_key: private_key.clone(),
            },
            Self::Vault {
                address,
                key,
                token_env,
                alg,
            } => SignerConfig::Vault {
                address: address.clone(),
                key: key.clone(),
                token_env: token_env.clone(),
                alg: alg.to_token_alg(),
            },
            Self::AwsKms { key_id, region } => SignerConfig::AwsKms {
                key_id: key_id.clone(),
                region: region.clone(),
            },
            Self::GcpKms {
                key_version,
                access_token_env,
            } => SignerConfig::GcpKms {
                key_version: key_version.clone(),
                access_token_env: access_token_env.clone(),
            },
            Self::AzureKv {
                vault_url,
                key,
                key_version,
                access_token_env,
            } => SignerConfig::AzureKv {
                vault_url: vault_url.clone(),
                key: key.clone(),
                key_version: key_version.clone(),
                access_token_env: access_token_env.clone(),
            },
            Self::Pkcs11 {
                module,
                token_label,
                key_label,
                pin_env,
                alg,
            } => SignerConfig::Pkcs11 {
                module: module.clone(),
                token_label: token_label.clone(),
                key_label: key_label.clone(),
                pin_env: pin_env.clone(),
                alg: alg.to_token_alg(),
            },
        }
    }
}

/// `serve` section — server defaults, overridden by flags/env.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ServeConfig {
    /// Bind address (e.g. `0.0.0.0:8080`).
    pub addr: Option<SocketAddr>,
    /// Data directory for filesystem backends.
    pub data_dir: Option<PathBuf>,
    /// Token root **private** key (hex) — issuing node: verifies *and* mints
    /// tokens / OIDC exchanges.
    pub auth_root_private_key: Option<String>,
    /// Token root **public** key (hex) — verify-only node.
    pub auth_root_public_key: Option<String>,
    /// Single-use bootstrap secret enabling `POST /api/tokens/bootstrap` (mint the
    /// first token without an admin bearer). Prefer the `BOATRAMP_BOOTSTRAP_SECRET`
    /// env / `--bootstrap-secret` flag so it isn't persisted in the config file.
    pub bootstrap_secret: Option<String>,
    /// External token signer (`[serve.signer]`): mint with a
    /// KMS/HSM/Vault-held root key instead of an in-process `auth_root_private_key`.
    /// Absent ⇒ the in-process key. When set, its public half is the trust anchor.
    pub signer: Option<AuthSignerConfig>,
    /// Reject blob uploads larger than this many bytes.
    pub max_upload_bytes: Option<u64>,
    /// Abort an upload that stalls for longer than this many seconds.
    pub upload_idle_timeout_secs: Option<u64>,
    /// Cap on simultaneous blob uploads.
    pub max_concurrent_uploads: Option<usize>,
    /// In a TLS mode, bind this plain-HTTP address on a second listener that
    /// redirects to HTTPS (dual-listener). Only read in `tls` builds.
    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
    pub http_redirect_addr: Option<SocketAddr>,
    /// Site to serve for a `Host` matching no domain, instead of 404.
    pub default_site: Option<String>,
    /// The fleet's canonical public origin (e.g. `https://cp.example.com`) that a
    /// per-request proof-of-possession must bind to (`aud`). Required for
    /// holder-bound (`cnf`/PoP) tokens to be usable — a proof's origin is compared
    /// against this value, never against a `Host`/`X-Forwarded-*` header.
    pub pop_origin: Option<String>,
    /// Require a valid control-plane token to view deployment previews.
    pub protect_previews: bool,
    /// Rate-limit cluster-wide via the control-plane KV instead of per node.
    pub cluster_rate_limit: bool,
    /// Keep the config cache coherent across processes sharing one KV via the
    /// changelog.
    pub shared_cache_coherence: bool,
    /// Cloud blob-change notification provisioning tier (FA-5b2): how boatramp
    /// obtains the native event pipeline (S3→SQS) that backs a `blob` trigger —
    /// `dry-run` (print the recipe), `provision` (create + retract), `verify-only`
    /// (operator pre-wired), or `refuse` (fail closed). Absent ⇒ no provisioning:
    /// `blob` triggers then work only on a self-watching backend (fs). Only wired
    /// for the S3 backend (`--features s3`).
    pub blob_notify_tier: Option<boatramp_core::blob_notify::ProvisionTier>,
    /// The AWS account id used to scope the provisioned SQS queue's `SendMessage`
    /// policy (`aws:SourceAccount`). Required when `blob_notify_tier` provisions.
    pub blob_notify_account_id: Option<String>,
    /// `[serve.console]` — the embedded web management console. Absent (or
    /// `enabled: false`) ⇒ not served. This is the **baseline** for the dynamic
    /// `console.*` daemon-config override, which can enable/move it at runtime
    /// (`boatramp config set console.enabled true`) without a restart.
    pub console: Option<ConsoleConfig>,
}

/// `[serve.console]` — the embedded web console (a Wasm SPA baked into the
/// binary with the `console` build feature). Opt-in: the static shell holds no
/// secrets and the `/api` it drives is token-gated, so it is served
/// **unauthenticated** at a deliberately obscure path (a bearer token can't gate
/// a top-level browser navigation anyway — the path is the obscurity, the token
/// is the real gate).
#[cfg_attr(not(feature = "console"), allow(dead_code))]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConsoleConfig {
    /// Serve the embedded console (default `false`). Requires the `console` build
    /// feature; enabling it in a build without that feature is a logged no-op.
    pub enabled: bool,
    /// Host(s) the console answers on: `*` (any host, the default), an exact host
    /// (`console.example.com`), or a leading-wildcard (`*.example.com`).
    pub host: Option<String>,
    /// URL path prefix the console mounts at (default `/_console`). Kept under the
    /// reserved `/_` namespace so it never collides with a published site path.
    pub path: Option<String>,
}

/// `publish` section — where and what to deploy (the `sync` target).
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct PublishConfig {
    /// Base URL of the boatramp server (e.g. `https://pad.example.com`).
    pub server: Option<String>,
    /// Site name to publish to.
    pub site: Option<String>,
    /// API token for the control plane (or set `BOATRAMP_TOKEN`).
    pub token: Option<String>,
    /// Project this site belongs to (overrides with `--project` / `BOATRAMP_PROJECT`).
    pub project: Option<String>,
}

/// `build` section.
#[derive(Debug, Clone, Deserialize)]
pub struct BuildConfig {
    /// Shell command to run (e.g. `npm run build`).
    pub command: String,
    /// Directory the build emits, published by `sync` (e.g. `dist`).
    #[serde(default)]
    pub output: Option<String>,
}

/// `bundle` section — the in-process Rust bundler (`bundler` feature).
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct BundleConfig {
    /// Output directory for bundled assets (e.g. `dist`).
    #[serde(default = "default_bundle_outdir")]
    pub outdir: String,
    /// JS/TS entry points bundled by Rolldown (tree-shaken, code-split).
    pub js: Vec<String>,
    /// CSS entry points bundled by lightningcss (`@import` inlined).
    pub css: Vec<String>,
    /// Minify output (default true).
    #[serde(default = "default_true")]
    pub minify: bool,
}

fn default_bundle_outdir() -> String {
    "dist".to_string()
}

fn default_true() -> bool {
    true
}

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

    fn project(text: &str) -> ProjectConfig {
        ron_options().from_str(text).unwrap()
    }

    fn server(text: &str) -> ServerConfig {
        ron_options().from_str(text).unwrap()
    }

    #[test]
    fn empty_project_config_is_default() {
        let cfg = project("()");
        assert!(cfg.publish.server.is_none());
        assert!(cfg.publish.site.is_none());
        assert!(cfg.build.is_none());
        assert!(cfg.bundle.is_none());
        // Routing defaults: schema v1, the single default index candidate.
        assert_eq!(cfg.routing.version, 1);
        assert_eq!(cfg.routing.index, vec!["index.html".to_string()]);
    }

    #[test]
    fn serve_signer_config_parses_and_maps_each_backend() {
        use boatramp_core::cose::TokenAlg;
        use boatramp_server::signer::SignerConfig;

        // RON-native enum tagging (`Vault(...)`); `IMPLICIT_SOME` lets the optional
        // fields (region) take a bare value or be omitted (→ None). This is the
        // exact RON documented in the Authentication guide.
        let vault = server(
            r#"( serve: ( signer: Vault(
                address: "https://vault.example:8200",
                key: "boatramp-root",
                token_env: "VAULT_TOKEN",
                alg: Ed25519,
            ) ) )"#,
        );
        match vault.serve.unwrap().signer.unwrap().to_signer_config() {
            SignerConfig::Vault {
                address,
                key,
                token_env,
                alg,
            } => {
                assert_eq!(address, "https://vault.example:8200");
                assert_eq!(key, "boatramp-root");
                assert_eq!(token_env, "VAULT_TOKEN");
                assert_eq!(alg, TokenAlg::Ed25519);
            }
            other => panic!("expected Vault, got {other:?}"),
        }

        // AWS KMS: region omitted → None; PKCS#11: alg omitted → the ES256 default.
        let aws =
            server(r#"( serve: ( signer: AwsKms(key_id: "arn:aws:kms:eu-west-1:1:key/abc") ) )"#);
        assert!(matches!(
            aws.serve.unwrap().signer.unwrap().to_signer_config(),
            SignerConfig::AwsKms { region: None, .. }
        ));

        let hsm = server(
            r#"( serve: ( signer: Pkcs11(
                module: "/usr/lib/softhsm/libsofthsm2.so",
                token_label: "boatramp",
                key_label: "root",
                pin_env: "HSM_PIN",
            ) ) )"#,
        );
        match hsm.serve.unwrap().signer.unwrap().to_signer_config() {
            SignerConfig::Pkcs11 { alg, .. } => assert_eq!(alg, TokenAlg::Es256),
            other => panic!("expected Pkcs11, got {other:?}"),
        }
    }

    #[test]
    fn project_config_parses_publish_build_and_routing() {
        let cfg = project(
            r#"(
                publish: ( server: "http://127.0.0.1:8080", site: "demo" ),
                build: ( command: "npm run build", output: "dist" ),
                routing: (
                    clean_urls: true,
                    redirects: [ (from: "/old/:slug", to: "/new/:slug", status: 301) ],
                ),
            )"#,
        );
        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
        assert_eq!(cfg.publish.site.as_deref(), Some("demo"));
        let build = cfg.build.unwrap();
        assert_eq!(build.command, "npm run build");
        assert_eq!(build.output.as_deref(), Some("dist"));
        assert!(cfg.routing.clean_urls);
        assert_eq!(cfg.routing.redirects.len(), 1);
        assert_eq!(cfg.routing.redirects[0].status, 301);
    }

    #[test]
    fn project_config_rejects_bad_routing_pattern() {
        // The same compile-check `load` runs: a bad route pattern is an error.
        let cfg = project(r#"( routing: ( redirects: [ (from: "/a/**/b/**", to: "/x") ] ) )"#);
        assert!(cfg.routing.compile_check().is_err());
    }

    #[test]
    fn empty_server_config_has_no_sections() {
        let cfg = server("()");
        assert!(cfg.serve.is_none());
        assert!(cfg.handlers.is_none());
        assert!(cfg.cluster.is_none());
        assert!(cfg.security.is_none());
    }

    #[test]
    fn security_section_parses_and_resolves() {
        // A profile plus an override that wins over it.
        let cfg = server(
            r#"(
                security: (
                    profile: "dev",
                    overrides: (
                        oidc_require_audience: true,
                        max_upload_bytes: 0,
                    ),
                )
            )"#,
        );
        let posture = cfg.security.unwrap().resolve().expect("resolves");
        // `dev` is loose...
        assert!(posture.allow_unauthenticated_public_bind);
        // ...but the explicit override wins over the profile.
        assert!(posture.oidc_require_audience);
        assert_eq!(posture.max_upload_bytes, 0); // unlimited
    }

    #[test]
    fn cluster_section_parses_the_dynamic_join_shape() {
        let cfg = server(
            r#"(
                cluster: (
                    listen: "10.0.0.2:7000",
                    root_pubkeys: ["es256:03a1"],
                    seeds: ["https://10.0.0.1:8080"],
                    join_token: "env:BOATRAMP_JOIN_TOKEN",
                ),
            )"#,
        );
        let cluster = cfg.cluster.unwrap();
        assert_eq!(
            cluster.listen,
            "10.0.0.2:7000".parse::<std::net::SocketAddr>().unwrap()
        );
        assert_eq!(cluster.root_pubkeys, vec!["es256:03a1".to_string()]);
        assert_eq!(cluster.seeds, vec!["https://10.0.0.1:8080".to_string()]);
        assert_eq!(
            cluster.join_token.as_deref(),
            Some("env:BOATRAMP_JOIN_TOKEN")
        );
        // store_dir defaults to None (→ <data-dir>/raft at serve time).
        assert!(cluster.store_dir.is_none());
    }

    #[test]
    fn cluster_section_founds_with_just_a_listen_addr() {
        // A founder needs no seeds/token — just where to bind the mesh.
        let cfg = server(r#"( cluster: ( listen: "0.0.0.0:7000" ) )"#);
        let cluster = cfg.cluster.unwrap();
        assert!(cluster.seeds.is_empty());
        assert!(cluster.root_pubkeys.is_empty());
        assert!(cluster.join_token.is_none());
    }

    #[test]
    fn sql_binding_single_node_defaults() {
        // A bare section (or none) means single-node: no url, default dir.
        let cfg = server(r#"( handlers: ( bindings: ( sql: () ) ) )"#);
        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
        assert!(sql.url.is_none());
        assert!(sql.dir.is_none());
    }

    #[test]
    fn sql_binding_single_node_custom_dir() {
        let cfg =
            server(r#"( handlers: ( bindings: ( sql: ( dir: "/var/lib/boatramp/sql" ) ) ) )"#);
        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
        assert_eq!(sql.dir.as_deref(), Some(Path::new("/var/lib/boatramp/sql")));
        assert!(sql.url.is_none());
    }

    #[test]
    fn sql_binding_cluster() {
        let cfg = server(
            r#"(
                handlers: ( bindings: ( sql: (
                    url: "http://sqld:8080",
                    admin_url: "http://sqld:9090",
                    token_env: "BOATRAMP_SQL_TOKEN",
                ) ) ),
            )"#,
        );
        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
        assert_eq!(sql.url.as_deref(), Some("http://sqld:8080"));
        assert_eq!(sql.admin_url.as_deref(), Some("http://sqld:9090"));
        assert_eq!(sql.token_env.as_deref(), Some("BOATRAMP_SQL_TOKEN"));
        assert_eq!(sql.admin_token_env, None);
    }

    #[test]
    fn sql_binding_preview_policy() {
        let cfg = server(
            r#"(
                handlers: ( bindings: ( sql: (
                    preview_mode: "branch",
                    preview_init: "/etc/boatramp/seed.sql",
                ) ) ),
            )"#,
        );
        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
        assert_eq!(sql.preview_mode.as_deref(), Some("branch"));
        assert_eq!(
            sql.preview_init.as_deref(),
            Some(Path::new("/etc/boatramp/seed.sql"))
        );
    }

    #[test]
    fn sql_binding_external_databases() {
        let cfg = server(
            r#"(
                handlers: ( bindings: ( sql: (
                    databases: {
                        "analytics": (
                            kind: "postgres",
                            url_env: "ANALYTICS_PG_URL",
                            pool_max: 16,
                            read_only: true,
                        ),
                        "events": (
                            kind: "mysql",
                            url_env: "EVENTS_MYSQL_URL",
                            read_url_env: "EVENTS_MYSQL_REPLICA_URL",
                            allow_preview: true,
                        ),
                    },
                ) ) ),
            )"#,
        );
        let sql = cfg.handlers.unwrap().bindings.sql.unwrap();
        assert_eq!(sql.databases.len(), 2);

        let analytics = &sql.databases["analytics"];
        assert_eq!(analytics.kind, "postgres");
        assert_eq!(analytics.url_env, "ANALYTICS_PG_URL");
        assert_eq!(analytics.pool_max, Some(16));
        assert!(analytics.read_only);
        assert!(!analytics.allow_preview);
        assert!(analytics.read_url_env.is_none());

        let events = &sql.databases["events"];
        assert_eq!(events.kind, "mysql");
        assert_eq!(
            events.read_url_env.as_deref(),
            Some("EVENTS_MYSQL_REPLICA_URL")
        );
        assert!(events.allow_preview);
        assert!(!events.read_only);
    }

    /// Path to a file at the repo root (two levels up from this crate).
    fn repo_root_file(name: &str) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join(name)
    }

    #[test]
    fn shipped_project_example_parses() {
        // The example we ship must always parse + compile-check, so it can't drift
        // from the schema.
        let text = std::fs::read_to_string(repo_root_file("examples/site/project.cfg.example"))
            .expect("example project config is present");
        let cfg = ProjectConfig::parse(&text).expect("example project config parses");
        assert_eq!(cfg.publish.server.as_deref(), Some("http://127.0.0.1:8080"));
        assert_eq!(cfg.build.as_ref().unwrap().command, "npm run build");
        assert_eq!(
            cfg.routing.error_documents.get(&404).map(String::as_str),
            Some("/404.html")
        );
    }

    #[test]
    fn shipped_server_example_parses() {
        let text = std::fs::read_to_string(repo_root_file("boatramp.cfg.example"))
            .expect("example server config is present");
        let cfg = ServerConfig::parse(&text).expect("example server config parses");
        let serve = cfg.serve.expect("example sets a serve section");
        assert_eq!(
            serve.addr,
            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
        );
    }

    #[test]
    fn secrets_section_parses_local_and_vault() {
        let local = server(r#"( secrets: ( envelope: "local", kek_file: "/k/kek" ) )"#)
            .secrets
            .expect("secrets section");
        assert_eq!(local.envelope, "local");
        assert_eq!(
            local.kek_file.as_deref(),
            Some(std::path::Path::new("/k/kek"))
        );

        let vault = server(
            r#"( secrets: ( envelope: "vault", vault: ( addr: "https://vault:8200", key: "certs" ) ) )"#,
        )
        .secrets
        .expect("secrets section");
        let v = vault.vault.expect("vault subsection");
        assert_eq!(v.addr, "https://vault:8200");
        assert_eq!(v.key, "certs");
        // The token env defaults to VAULT_TOKEN and is never in the file.
        assert_eq!(v.token_env, "VAULT_TOKEN");
    }

    #[test]
    fn serve_section_partial_parses() {
        // A partial `serve` section parses — unset fields take their defaults.
        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080", protect_previews: true ) )"#);
        let serve = cfg.serve.unwrap();
        assert_eq!(
            serve.addr,
            Some("0.0.0.0:8080".parse::<std::net::SocketAddr>().unwrap())
        );
        assert!(serve.protect_previews);
        assert!(!serve.cluster_rate_limit);
        assert!(serve.data_dir.is_none());
    }

    #[test]
    fn serve_console_config_parses() {
        // Absent ⇒ no console.
        let cfg = server(r#"( serve: ( addr: "0.0.0.0:8080" ) )"#);
        assert!(cfg.serve.unwrap().console.is_none());
        // Explicit console block with host + path.
        let cfg = server(
            r#"( serve: ( console: (
                enabled: true,
                host: "console.example.com",
                path: "/_console",
            ) ) )"#,
        );
        let console = cfg.serve.unwrap().console.unwrap();
        assert!(console.enabled);
        assert_eq!(console.host.as_deref(), Some("console.example.com"));
        assert_eq!(console.path.as_deref(), Some("/_console"));
        // Bare `enabled` ⇒ host/path take their (server-side) defaults.
        let cfg = server(r#"( serve: ( console: ( enabled: true ) ) )"#);
        let console = cfg.serve.unwrap().console.unwrap();
        assert!(console.enabled);
        assert!(console.host.is_none() && console.path.is_none());
    }
}