vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! Three-layer runtime configuration overlay.
//!
//! Implements **M0.8.1** of the VTC MVP Phase 0 plan. Spec §14.6
//! defines the effective-config precedence:
//!
//! ```text
//! effective = env > db_overrides > toml > defaults
//! ```
//!
//! This module owns the **db_overrides** layer (the `config`
//! keyspace) and the merge logic that combines all four layers into
//! the [`EffectiveConfig`] shape the admin endpoints surface.
//!
//! ## What's overlayable
//!
//! Every key the admin UX can `PATCH /v1/admin/config` against is
//! registered in [`REGISTRY`]. Phase 0 ships a small catalog —
//! `server.host`, `server.port`, `log.level`. More keys are added
//! mechanically as later phases introduce the underlying config
//! fields (status-list capacity, audit retention, membership
//! validity, etc.).
//!
//! Keys **not** in the registry are not addressable via PATCH and
//! don't appear in `GET /v1/admin/config`. Operators who need them
//! settable should add a registry entry alongside the field
//! definition.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use vti_common::error::AppError;
use vti_common::store::KeyspaceHandle;

use crate::config::AppConfig;
use crate::credentials::trusted_witnesses::WITNESSES_TRUSTED;

const STORAGE_PREFIX: &[u8] = b"config:override:";

fn storage_key(key: &str) -> Vec<u8> {
    let mut out = STORAGE_PREFIX.to_vec();
    out.extend_from_slice(key.as_bytes());
    out
}

// ---------------------------------------------------------------------------
// Registry
// ---------------------------------------------------------------------------

/// Where the **prior** value came from in the four-layer overlay.
/// Mirrors the variant on `vti_common::audit::ConfigSource` (M0.1.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ConfigSource {
    Env,
    Db,
    Toml,
    Default,
}

/// Permitted value shape for a registry entry. The PATCH validator
/// rejects values that don't match.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigKeyKind {
    /// Free-form string.
    String,
    /// Unsigned integer in `0..=u64::MAX` (PATCH accepts any JSON
    /// number; we coerce + range-check).
    U64,
    /// Unsigned integer constrained to `min..=max`, inclusive.
    ///
    /// Exists because a bare [`Self::U64`] accepts `0` and
    /// `u64::MAX` alike, and some keys have no sane reading at
    /// either end — a one-second idle timeout signs an operator out
    /// mid-keystroke, a ten-year one is not a timeout. Refusing at
    /// the API rather than in the console keeps the bound true for
    /// a scripted `config/patch` as well.
    U64Range { min: u64, max: u64 },
    /// A count constrained to `min..=max`, inclusive — [`Self::U64Range`] for a
    /// value that is not a duration, so the refusal does not call it seconds.
    CountRange { min: u64, max: u64 },
    /// `true` or `false`.
    Bool,
    /// Restricted set of strings — the value must be one of the
    /// listed variants. Useful for `log.level` ∈ {"trace", "debug",
    /// "info", "warn", "error"}.
    StringEnum(&'static [&'static str]),
    /// String constrained to start with one of the listed prefixes.
    /// The directory-allowlist gate for `server.tls.*` /
    /// `storage.path` (plan §14.6 — sensitive paths can't be
    /// pointed at arbitrary filesystem locations via the UX).
    PathAllowlist(&'static [&'static str]),
    /// A list of trusted witnesses: an array of `{ "did": "...", "label":
    /// "..." }` objects ([`crate::credentials::trusted_witnesses::parse_list`]).
    TrustedWitnessList,
}

/// Static metadata for one overlayable config key.
#[derive(Debug, Clone, Copy)]
pub struct ConfigKeyDef {
    /// Dotted path as the admin UX addresses it (e.g. `log.level`).
    pub key: &'static str,
    /// Permitted value shape.
    pub kind: ConfigKeyKind,
    /// `true` when changing this key requires a daemon restart to
    /// take effect (server bind, TLS cert, storage path …). PATCH
    /// still accepts the new value and stores it; the response's
    /// `pending_restart` list flags it for the caller.
    pub requires_restart: bool,
    /// `true` when the key's value should be redacted in audit
    /// events (plan **M0.1.5** ConfigChange::redact_if hook).
    /// Phase 0 has no sensitive keys yet — TLS paths land later
    /// alongside the actual `server.tls.*` config fields.
    pub sensitive: bool,
    /// `true` when the key alters trust, privacy, authority or security
    /// semantics — whose evidence counts, who is admitted, who may approve.
    /// VTI-CMP-090 treats such a change as materially an implementation change
    /// and VTI-CMP-092 requires it to be identifiable as one: a patch to one is
    /// logged at `warn` as a trust-semantics change beside its audit row.
    pub trust_semantics: bool,
}

/// Mirrors `vti_common::config`'s compiled-in default for
/// `auth.admin_idle_timeout`.
///
/// Duplicated rather than imported because the default fn there is
/// private, and the four-layer resolver needs the value in two places
/// (the default layer, and the "is the TOML value actually a default?"
/// test). Pinned against the real config by a unit test below, so the
/// copy cannot drift.
const DEFAULT_ADMIN_IDLE_TIMEOUT: u64 = 900;

/// The runtime key for [`crate::config::AclConfig::unrestricted_admin_consent_threshold`].
pub const UNRESTRICTED_ADMIN_CONSENT_THRESHOLD: &str = "acl.unrestricted_admin_consent_threshold";

/// The runtime key for [`crate::config::AclConfig::action_lifetime`] — how long
/// an operation parked for approval stays open (VTI-APV-008,
/// `vtc-action-list.md` §5).
pub const ACTION_LIFETIME: &str = "acl.action_lifetime";
/// The runtime key for [`crate::config::AclConfig::action_max_open_per_requester`].
pub const ACTION_MAX_OPEN_PER_REQUESTER: &str = "acl.action_max_open_per_requester";
/// The runtime key for [`crate::config::AclConfig::action_max_open`].
pub const ACTION_MAX_OPEN: &str = "acl.action_max_open";
/// The runtime key for [`crate::config::AclConfig::action_decline_cooldown`].
pub const ACTION_DECLINE_COOLDOWN: &str = "acl.action_decline_cooldown";
/// The runtime key for [`crate::config::AclConfig::removal_cooling_off`] — the
/// two-administrator cooling-off (VTI-APV-019, `vtc-action-list.md` §8.2).
pub const REMOVAL_COOLING_OFF: &str = "acl.removal_cooling_off";
/// The runtime key for [`crate::config::AclConfig::consent_request_push`].
pub const CONSENT_REQUEST_PUSH: &str = "acl.consent_request_push";

/// The action-list keys: `(key, env var, value in AppConfig)`. One table, so the
/// four overlay arms below cannot disagree about which keys exist.
fn action_key_value(key: &str, cfg: &AppConfig) -> Option<u64> {
    Some(match key {
        ACTION_LIFETIME => cfg.acl.action_lifetime,
        ACTION_MAX_OPEN_PER_REQUESTER => cfg.acl.action_max_open_per_requester,
        ACTION_MAX_OPEN => cfg.acl.action_max_open,
        ACTION_DECLINE_COOLDOWN => cfg.acl.action_decline_cooldown,
        REMOVAL_COOLING_OFF => cfg.acl.removal_cooling_off,
        _ => return None,
    })
}

fn action_key_default(key: &str) -> Option<u64> {
    Some(match key {
        ACTION_LIFETIME => crate::config::default_action_lifetime(),
        ACTION_MAX_OPEN_PER_REQUESTER => crate::config::default_action_max_open_per_requester(),
        ACTION_MAX_OPEN => crate::config::default_action_max_open(),
        ACTION_DECLINE_COOLDOWN => crate::config::default_action_decline_cooldown(),
        REMOVAL_COOLING_OFF => crate::config::default_removal_cooling_off(),
        _ => return None,
    })
}

fn action_key_env(key: &str) -> Option<&'static str> {
    Some(match key {
        ACTION_LIFETIME => "VTC_ACL_ACTION_LIFETIME",
        ACTION_MAX_OPEN_PER_REQUESTER => "VTC_ACL_ACTION_MAX_OPEN_PER_REQUESTER",
        ACTION_MAX_OPEN => "VTC_ACL_ACTION_MAX_OPEN",
        ACTION_DECLINE_COOLDOWN => "VTC_ACL_ACTION_DECLINE_COOLDOWN",
        REMOVAL_COOLING_OFF => "VTC_ACL_REMOVAL_COOLING_OFF",
        _ => return None,
    })
}

/// Write an action-list key's value into `cfg`. `false` when `key` is not one.
pub(crate) fn set_action_key(cfg: &mut AppConfig, key: &str, n: u64) -> bool {
    match key {
        ACTION_LIFETIME => cfg.acl.action_lifetime = n,
        ACTION_MAX_OPEN_PER_REQUESTER => cfg.acl.action_max_open_per_requester = n,
        ACTION_MAX_OPEN => cfg.acl.action_max_open = n,
        ACTION_DECLINE_COOLDOWN => cfg.acl.action_decline_cooldown = n,
        REMOVAL_COOLING_OFF => cfg.acl.removal_cooling_off = n,
        _ => return false,
    }
    true
}

/// The in-memory value of an action-list key, for the live view.
pub(crate) fn action_key_live(cfg: &AppConfig, key: &str) -> Option<u64> {
    action_key_value(key, cfg)
}

/// An action-list setting in force **now**: env, then the database layer, then
/// the in-memory value — read live, as [`live_consent_threshold`] is, so a
/// `config/patch` binds the next action without a reload. A stored value
/// outside the key's bounds (a corrupt row) is ignored for the in-memory one.
pub async fn live_action_setting(
    key: &str,
    cfg: &AppConfig,
    db: &ConfigStore,
) -> Result<u64, AppError> {
    let fallback = action_key_value(key, cfg)
        .ok_or_else(|| AppError::Internal(format!("{key} is not an action-list setting")))?;
    let layered = match env_layer_value(key) {
        Some(v) => Some(v),
        None => db.get(key).await?,
    };
    let in_bounds = |n: &u64| match lookup(key).map(|d| d.kind) {
        Some(ConfigKeyKind::U64Range { min, max } | ConfigKeyKind::CountRange { min, max }) => {
            (min..=max).contains(n)
        }
        _ => true,
    };
    Ok(layered
        .and_then(|v| v.as_u64())
        .filter(in_bounds)
        .unwrap_or(fallback))
}

/// The full catalog of UX-settable keys for Phase 0.
///
/// Adding a new key requires:
/// 1. The underlying field on [`crate::config::AppConfig`] (or a
///    sub-struct).
/// 2. An entry here.
/// 3. A new arm in [`compute_effective_value`] that pulls the toml-layer
///    value for the key.
/// 4. A new arm in [`apply_overrides`] that writes a db-layer value
///    back into [`AppConfig`].
///
/// Steps 3 + 4 are mechanical because the registry is small. A
/// future refactor can replace them with serde-driven reflection
/// when the catalog grows past ~20 keys.
pub const REGISTRY: &[ConfigKeyDef] = &[
    ConfigKeyDef {
        key: "server.host",
        kind: ConfigKeyKind::String,
        requires_restart: true,
        sensitive: false,
        trust_semantics: false,
    },
    ConfigKeyDef {
        key: "server.port",
        kind: ConfigKeyKind::U64,
        requires_restart: true,
        sensitive: false,
        trust_semantics: false,
    },
    ConfigKeyDef {
        key: "log.level",
        kind: ConfigKeyKind::StringEnum(&["trace", "debug", "info", "warn", "error"]),
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // The operational RP origin: the WebAuthn relying-party handle +
    // every VMC's `credentialStatus` status-list URL derive from it at
    // boot, so a change needs a restart. Canonical in the db-overlay
    // (P1.1 part 2b) — no longer round-tripped through `config.toml`.
    ConfigKeyDef {
        key: "public_url",
        kind: ConfigKeyKind::String,
        requires_restart: true,
        sensitive: false,
        trust_semantics: false,
    },
    // How long an admin console session may sit without user activity
    // before it stops being renewable. Hot-reloadable: `VtcAuthBackend`
    // re-reads `state.config` on every auth call, so a `config/patch` +
    // `config/reload` is in force on the next request.
    //
    // Bounded rather than free: below a minute an operator is signed out
    // between keystrokes, and beyond a day the value has stopped being a
    // timeout in any useful sense.
    ConfigKeyDef {
        key: "auth.admin_idle_timeout",
        kind: ConfigKeyKind::U64Range {
            min: 60,
            max: 86_400,
        },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // How many other unrestricted admins must consent to making someone an
    // unrestricted admin (VTI-APV-014). Read live by the gate, so no restart.
    //
    // No value switches the requirement off: the minimum is one other party.
    // The upper bound is a sanity cap, not a policy; the binding limit is the
    // community's own admin count, checked when the value is written
    // (`crate::acl::admin_consent::check_threshold_meetable`).
    ConfigKeyDef {
        key: UNRESTRICTED_ADMIN_CONSENT_THRESHOLD,
        kind: ConfigKeyKind::CountRange { min: 1, max: 16 },
        requires_restart: false,
        sensitive: false,
        trust_semantics: true,
    },
    // The action list (`vtc-action-list.md` §5, §7a.1). Each is read live by
    // `crate::admin_actions` when an action is raised, so none needs a restart,
    // and none reaches back to an open action: it keeps the `expiresAt` it was
    // raised with.
    //
    // VTI-APV-008: every action expires. Fifteen minutes is the shortest a
    // human can be reached in; fourteen days is the longest an approval
    // collected long ago may be spent on a community that has since moved on.
    ConfigKeyDef {
        key: ACTION_LIFETIME,
        kind: ConfigKeyKind::U64Range {
            min: 15 * 60,
            max: 14 * 24 * 3600,
        },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // Approval fatigue (§7a.1): a compromised administrator raising requests
    // until a tired approver clicks Approve.
    ConfigKeyDef {
        key: ACTION_MAX_OPEN_PER_REQUESTER,
        kind: ConfigKeyKind::CountRange { min: 1, max: 20 },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    ConfigKeyDef {
        key: ACTION_MAX_OPEN,
        kind: ConfigKeyKind::CountRange { min: 10, max: 500 },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    ConfigKeyDef {
        key: ACTION_DECLINE_COOLDOWN,
        kind: ConfigKeyKind::U64Range {
            min: 0,
            max: 24 * 3600,
        },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // The two-administrator cooling-off (VTI-APV-019, §8.2): how long an
    // unopposed reduction of an unrestricted administrator waits before it
    // lands. Zero lands it at once; a week is the most a removal of a
    // compromised co-administrator may be held up.
    ConfigKeyDef {
        key: REMOVAL_COOLING_OFF,
        kind: ConfigKeyKind::U64Range {
            min: 0,
            max: 7 * 24 * 3600,
        },
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // Whether a raised action is also pushed to approvers' devices (§11.6).
    // Off by default: the action list is the source of truth.
    ConfigKeyDef {
        key: CONSENT_REQUEST_PUSH,
        kind: ConfigKeyKind::Bool,
        requires_restart: false,
        sensitive: false,
        trust_semantics: false,
    },
    // The witnesses whose VWCs count here
    // (`crate::credentials::trusted_witnesses`). Read live on every VWC, so no
    // restart. Empty — the default — trusts none.
    ConfigKeyDef {
        key: WITNESSES_TRUSTED,
        kind: ConfigKeyKind::TrustedWitnessList,
        requires_restart: false,
        sensitive: false,
        trust_semantics: true,
    },
];

/// `acl.single_admin_mode` — single-administrator mode (VTI-APV-022). **Not**
/// in [`REGISTRY`]: the mode must be set only by a party with host access and
/// never through the operation surface (item 1), so `config/patch` and
/// `vtc/config/import` refuse it by name ([`host_only_refusal`]).
pub const SINGLE_ADMIN_MODE: &str = "acl.single_admin_mode";

/// Why `key` is refused on the operation surface, when it is a host-only key —
/// the refusal names how to set it instead. `None` for every other key.
pub fn host_only_refusal(key: &str) -> Option<String> {
    (key == SINGLE_ADMIN_MODE).then(|| {
        format!(
            "{SINGLE_ADMIN_MODE} is host configuration and cannot be set or cleared through              the operation surface (VTI-APV-022). With access to the host, set `[acl]              single_admin_mode = true` (or remove it) in config.toml and restart the daemon"
        )
    })
}

/// Look up a key's metadata. `None` means the key is not
/// overlayable.
pub fn lookup(key: &str) -> Option<&'static ConfigKeyDef> {
    REGISTRY.iter().find(|d| d.key == key)
}

// ---------------------------------------------------------------------------
// ConfigStore
// ---------------------------------------------------------------------------

/// Wraps the `config` keyspace with the db-overlay-layer ops.
/// Cheap to clone (handle is `Arc`-shared internally).
#[derive(Clone)]
pub struct ConfigStore {
    ks: KeyspaceHandle,
}

impl ConfigStore {
    pub fn new(ks: KeyspaceHandle) -> Self {
        Self { ks }
    }

    /// Read a single db-layer override, if any.
    pub async fn get(&self, key: &str) -> Result<Option<Value>, AppError> {
        self.ks.get(storage_key(key)).await
    }

    /// Write (insert or replace) a db-layer override.
    pub async fn put(&self, key: &str, value: &Value) -> Result<(), AppError> {
        self.ks.insert(storage_key(key), value).await?;
        // `vtc/config/export` reads these (`crate::admin_events`).
        crate::admin_events::notify(crate::admin_events::Topic::Config);
        Ok(())
    }

    /// Remove a db-layer override. After this call, the effective
    /// value comes from the lower-priority layer (env, toml, or
    /// default).
    pub async fn delete(&self, key: &str) -> Result<(), AppError> {
        self.ks.remove(storage_key(key)).await?;
        crate::admin_events::notify(crate::admin_events::Topic::Config);
        Ok(())
    }

    /// Snapshot every db-layer override. Used by
    /// [`compute_effective_config`] to avoid one round-trip per
    /// key during GET.
    pub async fn snapshot(&self) -> Result<HashMap<String, Value>, AppError> {
        let pairs = self.ks.prefix_iter_raw(STORAGE_PREFIX.to_vec()).await?;
        let prefix_len = STORAGE_PREFIX.len();
        let mut out = HashMap::with_capacity(pairs.len());
        for (key_bytes, value_bytes) in pairs {
            let Some(rest) = key_bytes.get(prefix_len..) else {
                continue;
            };
            let Ok(name) = String::from_utf8(rest.to_vec()) else {
                tracing::warn!("skipping non-UTF-8 config-override key");
                continue;
            };
            let Ok(value) = serde_json::from_slice::<Value>(&value_bytes) else {
                tracing::warn!(key = %name, "skipping unparseable config-override value");
                continue;
            };
            out.insert(name, value);
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// Effective config view
// ---------------------------------------------------------------------------

/// One field in the merged [`EffectiveConfig`] view. Per spec §14.6
/// the admin UX needs both the value and the *source* layer so an
/// operator can tell whether the running value was set in TOML, by
/// an env override, by a PATCH against the DB layer, or fell back
/// to the compiled-in default.
#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct EffectiveField {
    pub key: String,
    pub value: Value,
    pub source: ConfigSource,
    pub requires_restart: bool,
}

/// Response shape for `GET /v1/admin/config` — every registry key
/// resolved through the four-layer overlay.
#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
pub struct EffectiveConfig {
    pub fields: Vec<EffectiveField>,
}

/// Pull the TOML-layer value for `key` from `cfg`. Returns `None`
/// when the field is at its compiled-in default (so the merge
/// algorithm can attribute the value to `Default` instead of
/// `Toml`).
///
/// Mechanically maintained: one arm per registry key. See
/// [`REGISTRY`] for the catalog.
fn toml_layer_value(key: &str, cfg: &AppConfig) -> Option<Value> {
    use crate::config::default_host_value;
    use crate::config::default_port_value;
    match key {
        "server.host" => {
            if cfg.server.host == default_host_value() {
                None
            } else {
                Some(Value::String(cfg.server.host.clone()))
            }
        }
        "server.port" => {
            if cfg.server.port == default_port_value() {
                None
            } else {
                Some(Value::Number(serde_json::Number::from(cfg.server.port)))
            }
        }
        "log.level" => {
            // `LogConfig::level` defaults to `"info"`; treat that
            // as the compiled-in default.
            if cfg.log.level == "info" {
                None
            } else {
                Some(Value::String(cfg.log.level.clone()))
            }
        }
        // `public_url` has no compiled-in default — `None` (unset) is the
        // default, so any configured value is the toml-layer value.
        "public_url" => cfg.public_url.clone().map(Value::String),
        UNRESTRICTED_ADMIN_CONSENT_THRESHOLD => {
            let n = cfg.acl.unrestricted_admin_consent_threshold;
            (n != crate::config::default_unrestricted_admin_consent_threshold())
                .then(|| Value::Number(serde_json::Number::from(n)))
        }
        CONSENT_REQUEST_PUSH => cfg.acl.consent_request_push.then_some(Value::Bool(true)),
        WITNESSES_TRUSTED => (!cfg.witnesses.is_empty())
            .then(|| serde_json::to_value(&cfg.witnesses.trusted).unwrap_or(Value::Null)),
        "auth.admin_idle_timeout" => {
            if cfg.auth.admin_idle_timeout == DEFAULT_ADMIN_IDLE_TIMEOUT {
                None
            } else {
                Some(Value::Number(serde_json::Number::from(
                    cfg.auth.admin_idle_timeout,
                )))
            }
        }
        other => {
            let n = action_key_value(other, cfg)?;
            (Some(n) != action_key_default(other)).then(|| Value::Number(n.into()))
        }
    }
}

/// Compiled-in default for `key`. Always returns a value (every
/// registered key has a default).
fn default_layer_value(key: &str) -> Value {
    use crate::config::default_host_value;
    use crate::config::default_port_value;
    match key {
        "server.host" => Value::String(default_host_value()),
        "server.port" => Value::Number(serde_json::Number::from(default_port_value())),
        "log.level" => Value::String("info".into()),
        // No compiled-in default: `null` means "unset" (pre-setup
        // deployment — WebAuthn / status lists deferred).
        "public_url" => Value::Null,
        UNRESTRICTED_ADMIN_CONSENT_THRESHOLD => Value::Number(serde_json::Number::from(
            crate::config::default_unrestricted_admin_consent_threshold(),
        )),
        "auth.admin_idle_timeout" => {
            Value::Number(serde_json::Number::from(DEFAULT_ADMIN_IDLE_TIMEOUT))
        }
        CONSENT_REQUEST_PUSH => Value::Bool(false),
        WITNESSES_TRUSTED => Value::Array(Vec::new()),
        other => match action_key_default(other) {
            Some(n) => Value::Number(n.into()),
            None => Value::Null, // unreachable for registry keys
        },
    }
}

/// Env-layer override for `key`, if the operator has set the
/// matching `VTC_*` variable. The names match what
/// [`AppConfig::load`] already consults so the merge view is
/// consistent with what the daemon actually loaded.
fn env_layer_value(key: &str) -> Option<Value> {
    match key {
        "server.host" => std::env::var("VTC_SERVER_HOST").ok().map(Value::String),
        "server.port" => std::env::var("VTC_SERVER_PORT")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map(|n| Value::Number(serde_json::Number::from(n))),
        "log.level" => std::env::var("VTC_LOG_LEVEL").ok().map(Value::String),
        "public_url" => std::env::var("VTC_PUBLIC_URL").ok().map(Value::String),
        UNRESTRICTED_ADMIN_CONSENT_THRESHOLD => {
            std::env::var("VTC_ACL_UNRESTRICTED_ADMIN_CONSENT_THRESHOLD")
                .ok()
                .and_then(|s| s.parse::<u64>().ok())
                .map(|n| Value::Number(serde_json::Number::from(n)))
        }
        CONSENT_REQUEST_PUSH => std::env::var("VTC_ACL_CONSENT_REQUEST_PUSH")
            .ok()
            .and_then(|s| s.parse::<bool>().ok())
            .map(Value::Bool),
        // A list has no environment form; it is set in TOML or patched.
        WITNESSES_TRUSTED => None,
        "auth.admin_idle_timeout" => std::env::var("VTC_AUTH_ADMIN_IDLE_TIMEOUT")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map(|n| Value::Number(serde_json::Number::from(n))),
        other => std::env::var(action_key_env(other)?)
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map(|n| Value::Number(serde_json::Number::from(n))),
    }
}

/// Whether consent requests are pushed to approvers' devices **now**: env, then
/// the database layer, then the in-memory value — read live, so a
/// `config/patch` binds the next action without a reload. A stored value that
/// is not a boolean (a corrupt row) is ignored for the in-memory one.
pub async fn live_consent_request_push(
    cfg: &AppConfig,
    db: &ConfigStore,
) -> Result<bool, AppError> {
    let layered = match env_layer_value(CONSENT_REQUEST_PUSH) {
        Some(v) => Some(v),
        None => db.get(CONSENT_REQUEST_PUSH).await?,
    };
    Ok(layered
        .and_then(|v| v.as_bool())
        .unwrap_or(cfg.acl.consent_request_push))
}

/// The unrestricted-admin consent threshold in force now: env, then the database
/// layer, then `fallback` (the in-memory value, which carries TOML or the
/// default). Below 1 never comes back — a corrupt row is not read as "no consent
/// needed".
pub async fn live_consent_threshold(fallback: u64, db: &ConfigStore) -> Result<u64, AppError> {
    let layered = match env_layer_value(UNRESTRICTED_ADMIN_CONSENT_THRESHOLD) {
        Some(v) => Some(v),
        None => db.get(UNRESTRICTED_ADMIN_CONSENT_THRESHOLD).await?,
    };
    Ok(layered
        .and_then(|v| v.as_u64())
        .filter(|n| *n >= 1)
        .unwrap_or(fallback.max(1)))
}

/// Compute the four-layer-merged view for every registry key.
pub async fn compute_effective_config(
    cfg: &AppConfig,
    db: &ConfigStore,
) -> Result<EffectiveConfig, AppError> {
    let db_snapshot = db.snapshot().await?;
    let mut fields = Vec::with_capacity(REGISTRY.len());

    for def in REGISTRY {
        let (value, source) = if let Some(v) = env_layer_value(def.key) {
            (v, ConfigSource::Env)
        } else if let Some(v) = db_snapshot.get(def.key) {
            (v.clone(), ConfigSource::Db)
        } else if let Some(v) = toml_layer_value(def.key, cfg) {
            (v, ConfigSource::Toml)
        } else {
            (default_layer_value(def.key), ConfigSource::Default)
        };

        fields.push(EffectiveField {
            key: def.key.into(),
            value,
            source,
            requires_restart: def.requires_restart,
        });
    }

    Ok(EffectiveConfig { fields })
}

// ---------------------------------------------------------------------------
// Boot-time override application
// ---------------------------------------------------------------------------

/// Write the resolved (effective) `value` for `key` back into the
/// in-memory [`AppConfig`]. The inverse of [`toml_layer_value`] — one
/// arm per registry key (the step-4 the [`REGISTRY`] doc references).
///
/// A type mismatch is skipped rather than panicked: the value was
/// validated by the PATCH that stored it, so a mismatch here means a
/// corrupt row, and a corrupt row must not take down boot.
fn set_app_config_field(cfg: &mut AppConfig, key: &str, value: &Value) {
    match key {
        "server.host" => {
            if let Some(s) = value.as_str() {
                cfg.server.host = s.to_string();
            }
        }
        "server.port" => match value.as_u64().and_then(|n| u16::try_from(n).ok()) {
            Some(p) => cfg.server.port = p,
            None => tracing::warn!(
                %value,
                "config override `server.port` is not a valid u16 — ignored"
            ),
        },
        "log.level" => {
            if let Some(s) = value.as_str() {
                cfg.log.level = s.to_string();
            }
        }
        // A string sets it; `null` (the default layer, i.e. unset) leaves
        // it `None`. A configured value resolves via `toml_layer_value`,
        // so an absent db override never clears a TOML-set `public_url`.
        "public_url" => {
            cfg.public_url = value.as_str().map(str::to_string);
        }
        // Below 1 is refused at write; a row that says otherwise is corrupt and
        // must not be read as "no consent needed".
        UNRESTRICTED_ADMIN_CONSENT_THRESHOLD => match value.as_u64() {
            Some(n) if n >= 1 => cfg.acl.unrestricted_admin_consent_threshold = n,
            _ => tracing::warn!(
                %value,
                "config override `{UNRESTRICTED_ADMIN_CONSENT_THRESHOLD}` is not a count of at \
                 least 1 — ignored"
            ),
        },
        CONSENT_REQUEST_PUSH => match value.as_bool() {
            Some(b) => cfg.acl.consent_request_push = b,
            None => tracing::warn!(
                %value,
                "config override `{CONSENT_REQUEST_PUSH}` is not a boolean — ignored"
            ),
        },
        // A row that does not parse is ignored here, and the live reader
        // (`trusted_witnesses::live`) reads the same row as trusting nobody.
        WITNESSES_TRUSTED => {
            match crate::credentials::trusted_witnesses::parse_list(value, cfg.vtc_did.as_deref()) {
                Ok(list) => cfg.witnesses.trusted = list,
                Err(e) => tracing::warn!(
                    error = %e,
                    "config override `{WITNESSES_TRUSTED}` is not a valid witness list — ignored"
                ),
            }
        }
        "auth.admin_idle_timeout" => match value.as_u64() {
            Some(n) => cfg.auth.admin_idle_timeout = n,
            None => tracing::warn!(
                %value,
                "config override `auth.admin_idle_timeout` is not a u64 — ignored"
            ),
        },
        other => {
            if action_key_value(other, cfg).is_some() {
                match value.as_u64() {
                    Some(n) => {
                        set_action_key(cfg, other, n);
                    }
                    None => tracing::warn!(
                        %value,
                        key = other,
                        "config override is not a u64 — ignored"
                    ),
                }
            }
        }
    }
}

/// Fold the db-overlay (the `config` keyspace) onto the in-memory
/// [`AppConfig`] at boot, so an operator's runtime PATCHes actually
/// take effect.
///
/// This is the step that makes `config_store` **canonical** (P1.1):
/// without it a `PATCH /v1/admin/config` against a `requires_restart`
/// key (the server bind host/port) is stored but never applied — even
/// after the restart it asks for, because boot read only TOML + env.
/// Resolves every registry key through the same
/// `env > db > toml > default` precedence [`compute_effective_config`]
/// uses, then writes the resolved value back into `cfg`.
///
/// **`log.level` caveat:** the tracing subscriber is initialised from
/// `cfg.log.level` in `main` *before* this runs, so a db-override of
/// `log.level` updates the in-memory config but not the already-live
/// filter — wiring the subscriber reload is the same separate follow-up
/// `reload_config` documents.
pub async fn apply_overrides(cfg: &mut AppConfig, db: &ConfigStore) -> Result<(), AppError> {
    let eff = compute_effective_config(cfg, db).await?;
    for field in eff.fields {
        set_app_config_field(cfg, &field.key, &field.value);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Validate that `value` matches `def.kind`. Returns a structured
/// `AppError::Validation` on mismatch.
pub fn validate_value(def: &ConfigKeyDef, value: &Value) -> Result<(), AppError> {
    match def.kind {
        ConfigKeyKind::String => {
            if !value.is_string() {
                return Err(AppError::Validation(format!(
                    "{} must be a string",
                    def.key
                )));
            }
            Ok(())
        }
        ConfigKeyKind::U64 => match value.as_u64() {
            Some(_) => Ok(()),
            None => Err(AppError::Validation(format!(
                "{} must be an unsigned integer",
                def.key
            ))),
        },
        ConfigKeyKind::U64Range { min, max } => match value.as_u64() {
            Some(n) if (min..=max).contains(&n) => Ok(()),
            Some(n) => Err(AppError::Validation(format!(
                "{} must be between {min} and {max} seconds, got {n}",
                def.key
            ))),
            None => Err(AppError::Validation(format!(
                "{} must be an unsigned integer",
                def.key
            ))),
        },
        ConfigKeyKind::CountRange { min, max } => match value.as_u64() {
            Some(n) if (min..=max).contains(&n) => Ok(()),
            Some(n) => Err(AppError::Validation(format!(
                "{} must be between {min} and {max}, got {n}",
                def.key
            ))),
            None => Err(AppError::Validation(format!(
                "{} must be an unsigned integer",
                def.key
            ))),
        },
        ConfigKeyKind::Bool => match value.as_bool() {
            Some(_) => Ok(()),
            None => Err(AppError::Validation(format!(
                "{} must be true or false",
                def.key
            ))),
        },
        ConfigKeyKind::StringEnum(allowed) => {
            let s = value
                .as_str()
                .ok_or_else(|| AppError::Validation(format!("{} must be a string", def.key)))?;
            if allowed.contains(&s) {
                Ok(())
            } else {
                Err(AppError::Validation(format!(
                    "{} must be one of {:?}, got {:?}",
                    def.key, allowed, s
                )))
            }
        }
        ConfigKeyKind::PathAllowlist(prefixes) => {
            let s = value
                .as_str()
                .ok_or_else(|| AppError::Validation(format!("{} must be a string", def.key)))?;
            if prefixes.iter().any(|p| s.starts_with(p)) {
                Ok(())
            } else {
                Err(AppError::Validation(format!(
                    "{} must start with one of {:?}",
                    def.key, prefixes
                )))
            }
        }
        // The community's own DID is refused by the caller, which knows it
        // (`routes::admin::config::check_against_community`).
        ConfigKeyKind::TrustedWitnessList => {
            crate::credentials::trusted_witnesses::parse_list(value, None)
                .map(|_| ())
                .map_err(|e| AppError::Validation(format!("{}: {e}", def.key)))
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use vti_common::config::StoreConfig;
    use vti_common::store::Store;

    fn temp_store() -> (ConfigStore, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let cfg = StoreConfig {
            data_dir: dir.path().to_path_buf(),
        };
        let store = Store::open(&cfg).expect("store");
        let ks = store.keyspace("config-test").expect("ks");
        (ConfigStore::new(ks), dir)
    }

    fn default_app_config() -> AppConfig {
        toml::from_str("").expect("empty TOML parses")
    }

    // ── auth.admin_idle_timeout ──

    /// The registry keeps its own copy of the compiled-in default
    /// because `vti_common`'s default fn is private. Pin the two
    /// together: if the shared default moves and this copy does not,
    /// the default layer starts reporting a value the daemon is not
    /// actually running with, and `toml_layer_value` starts calling a
    /// genuine operator setting a "default" (or vice versa).
    #[test]
    fn registry_default_matches_the_real_config_default() {
        let cfg = default_app_config();
        assert_eq!(
            cfg.auth.admin_idle_timeout, DEFAULT_ADMIN_IDLE_TIMEOUT,
            "DEFAULT_ADMIN_IDLE_TIMEOUT has drifted from vti_common's default"
        );
    }

    #[test]
    fn idle_timeout_rejects_values_outside_the_bounds() {
        let def = lookup("auth.admin_idle_timeout").expect("key is registered");
        // A timeout shorter than a minute signs an operator out between
        // keystrokes; one longer than a day is not a timeout.
        assert!(validate_value(def, &json!(59)).is_err());
        assert!(validate_value(def, &json!(86_401)).is_err());
        assert!(validate_value(def, &json!(0)).is_err());
        assert!(validate_value(def, &json!("900")).is_err());
        // The bounds themselves are inclusive.
        assert!(validate_value(def, &json!(60)).is_ok());
        assert!(validate_value(def, &json!(86_400)).is_ok());
        assert!(validate_value(def, &json!(1800)).is_ok());
    }

    #[test]
    fn idle_timeout_error_names_the_bounds_it_wants() {
        let def = lookup("auth.admin_idle_timeout").expect("key is registered");
        let err = validate_value(def, &json!(5)).unwrap_err().to_string();
        // An operator who set a bad value should be told the range, not
        // just that they were wrong.
        assert!(err.contains("60"), "{err}");
        assert!(err.contains("86400"), "{err}");
    }

    #[tokio::test]
    async fn idle_timeout_db_override_reaches_the_live_config() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        assert_eq!(cfg.auth.admin_idle_timeout, DEFAULT_ADMIN_IDLE_TIMEOUT);

        store
            .put("auth.admin_idle_timeout", &json!(1800))
            .await
            .unwrap();
        apply_overrides(&mut cfg, &store).await.unwrap();

        assert_eq!(cfg.auth.admin_idle_timeout, 1800);
    }

    #[tokio::test]
    async fn idle_timeout_is_hot_reloadable() {
        let def = lookup("auth.admin_idle_timeout").expect("key is registered");
        assert!(
            !def.requires_restart,
            "the console's Save does PATCH + reload; a restart-only key would \
             report success and change nothing until the daemon bounced"
        );
    }

    // ── ConfigStore CRUD ──

    #[tokio::test]
    async fn put_then_get_returns_value() {
        let (store, _dir) = temp_store();
        store.put("log.level", &json!("debug")).await.unwrap();
        let got = store.get("log.level").await.unwrap();
        assert_eq!(got, Some(json!("debug")));
    }

    #[tokio::test]
    async fn delete_removes_value() {
        let (store, _dir) = temp_store();
        store.put("log.level", &json!("debug")).await.unwrap();
        store.delete("log.level").await.unwrap();
        let got = store.get("log.level").await.unwrap();
        assert!(got.is_none());
    }

    #[tokio::test]
    async fn snapshot_returns_all_overrides() {
        let (store, _dir) = temp_store();
        store.put("log.level", &json!("debug")).await.unwrap();
        store.put("server.host", &json!("10.0.0.1")).await.unwrap();
        let snap = store.snapshot().await.unwrap();
        assert_eq!(snap.len(), 2);
        assert_eq!(snap.get("log.level"), Some(&json!("debug")));
        assert_eq!(snap.get("server.host"), Some(&json!("10.0.0.1")));
    }

    // ── Validation ──

    #[test]
    fn validate_string_kind() {
        let def = lookup("server.host").unwrap();
        assert!(validate_value(def, &json!("0.0.0.0")).is_ok());
        assert!(validate_value(def, &json!(42)).is_err());
    }

    #[test]
    fn validate_u64_kind() {
        let def = lookup("server.port").unwrap();
        assert!(validate_value(def, &json!(8200)).is_ok());
        assert!(validate_value(def, &json!(-1)).is_err());
        assert!(validate_value(def, &json!("8200")).is_err());
    }

    #[test]
    fn validate_string_enum_kind() {
        let def = lookup("log.level").unwrap();
        for lvl in ["trace", "debug", "info", "warn", "error"] {
            assert!(
                validate_value(def, &json!(lvl)).is_ok(),
                "{lvl} should pass"
            );
        }
        assert!(validate_value(def, &json!("verbose")).is_err());
        assert!(validate_value(def, &json!(42)).is_err());
    }

    // ── Effective-config layering ──

    #[tokio::test]
    async fn effective_returns_defaults_when_no_overrides() {
        let (store, _dir) = temp_store();
        let cfg = default_app_config();
        let eff = compute_effective_config(&cfg, &store).await.unwrap();

        let by_key: HashMap<_, _> = eff.fields.iter().map(|f| (&*f.key, f)).collect();
        assert_eq!(by_key["server.host"].source, ConfigSource::Default);
        assert_eq!(by_key["server.host"].value, json!("0.0.0.0"));
        assert_eq!(by_key["server.port"].source, ConfigSource::Default);
        assert_eq!(by_key["server.port"].value, json!(8200));
        assert_eq!(by_key["log.level"].source, ConfigSource::Default);
        assert_eq!(by_key["log.level"].value, json!("info"));
    }

    #[tokio::test]
    async fn db_layer_beats_toml() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.log.level = "debug".into(); // toml-layer override

        // db-layer override wins.
        store.put("log.level", &json!("warn")).await.unwrap();

        let eff = compute_effective_config(&cfg, &store).await.unwrap();
        let f = eff.fields.iter().find(|f| f.key == "log.level").unwrap();
        assert_eq!(f.source, ConfigSource::Db);
        assert_eq!(f.value, json!("warn"));
    }

    #[tokio::test]
    async fn toml_layer_used_when_no_db_override() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.log.level = "debug".into();

        let eff = compute_effective_config(&cfg, &store).await.unwrap();
        let f = eff.fields.iter().find(|f| f.key == "log.level").unwrap();
        assert_eq!(f.source, ConfigSource::Toml);
        assert_eq!(f.value, json!("debug"));
    }

    #[tokio::test]
    async fn requires_restart_flag_propagates_from_registry() {
        let (store, _dir) = temp_store();
        let cfg = default_app_config();
        let eff = compute_effective_config(&cfg, &store).await.unwrap();

        let host = eff.fields.iter().find(|f| f.key == "server.host").unwrap();
        assert!(host.requires_restart);
        let level = eff.fields.iter().find(|f| f.key == "log.level").unwrap();
        assert!(!level.requires_restart);
    }

    // ── apply_overrides (P1.1: boot folds the db overlay onto AppConfig) ──

    #[tokio::test]
    async fn apply_overrides_writes_db_layer_into_config() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        assert_eq!(cfg.server.host, "0.0.0.0");
        assert_eq!(cfg.server.port, 8200);

        store.put("server.host", &json!("10.0.0.5")).await.unwrap();
        store.put("server.port", &json!(9100)).await.unwrap();
        store.put("log.level", &json!("debug")).await.unwrap();

        apply_overrides(&mut cfg, &store).await.unwrap();

        assert_eq!(cfg.server.host, "10.0.0.5");
        assert_eq!(cfg.server.port, 9100);
        assert_eq!(cfg.log.level, "debug");
    }

    #[tokio::test]
    async fn apply_overrides_preserves_toml_when_no_db_override() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.server.host = "192.168.1.1".into(); // toml-layer value
        cfg.server.port = 8443;

        apply_overrides(&mut cfg, &store).await.unwrap();

        assert_eq!(cfg.server.host, "192.168.1.1");
        assert_eq!(cfg.server.port, 8443);
    }

    #[tokio::test]
    async fn apply_overrides_db_beats_toml() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.server.port = 8443; // toml-layer
        store.put("server.port", &json!(9100)).await.unwrap();

        apply_overrides(&mut cfg, &store).await.unwrap();

        assert_eq!(cfg.server.port, 9100, "db override must win over toml");
    }

    #[tokio::test]
    async fn apply_overrides_ignores_out_of_range_port() {
        // The U64 registry kind accepts any u64, but the field is u16 —
        // a stored 70000 is a corrupt row and must not be applied.
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.server.port = 8443;
        store.put("server.port", &json!(70_000)).await.unwrap();

        apply_overrides(&mut cfg, &store).await.unwrap();

        assert_eq!(cfg.server.port, 8443, "out-of-range port override ignored");
    }

    #[tokio::test]
    async fn apply_overrides_public_url_db_beats_toml_and_preserves_toml() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        cfg.public_url = Some("https://toml.example".into()); // toml-layer

        // No db override → toml value preserved.
        apply_overrides(&mut cfg, &store).await.unwrap();
        assert_eq!(cfg.public_url.as_deref(), Some("https://toml.example"));

        // db override wins.
        store
            .put("public_url", &json!("https://db.example"))
            .await
            .unwrap();
        apply_overrides(&mut cfg, &store).await.unwrap();
        assert_eq!(cfg.public_url.as_deref(), Some("https://db.example"));
    }

    #[tokio::test]
    async fn apply_overrides_public_url_unset_stays_none() {
        let (store, _dir) = temp_store();
        let mut cfg = default_app_config();
        assert!(cfg.public_url.is_none());
        // No db override + no toml value → default layer (null) → stays None,
        // never spuriously set to an empty string.
        apply_overrides(&mut cfg, &store).await.unwrap();
        assert!(
            cfg.public_url.is_none(),
            "no override → public_url stays unset"
        );
    }
}