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
use crate::error::AppError;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
// Re-export shared config types so existing code can still use `crate::config::*`
pub use did_hosting_common::server::config::{
AuthConfig, FeaturesConfig, FjallTuning, HostingConfig, LogConfig, LogFormat, SecretsConfig,
ServerConfig, StoreConfig, TransportSelection, VtaConfig,
};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AppConfig {
#[serde(default)]
pub features: FeaturesConfig,
pub server_did: Option<String>,
pub mediator_did: Option<String>,
pub public_url: Option<String>,
#[serde(default)]
pub server: ServerConfig,
#[serde(default)]
pub log: LogConfig,
#[serde(default)]
pub store: StoreConfig,
/// Optional Fjall memory tuning (`[fjall]`) — the block cache, write
/// buffer and journal-size caps that keep the store's memory use
/// inside a pod's Kubernetes limit. Every field defaults to `None`
/// (fjall's own defaults, unchanged). See
/// [`did_hosting_common::server::config::FjallTuning`].
#[serde(default)]
pub fjall: FjallTuning,
#[serde(default)]
pub auth: AuthConfig,
/// Multi-domain hosting (bootstrap_domains + unassigned_purge_grace).
/// Daemon mode already exposes this via its own DaemonConfig; the
/// standalone server gains it here so T28's unassignment handler
/// (which lives in `did-hosting-server::messaging`) can read the
/// grace duration uniformly.
#[serde(default)]
pub hosting: HostingConfig,
#[serde(default)]
pub secrets: SecretsConfig,
#[serde(default)]
pub limits: LimitsConfig,
#[serde(default)]
pub stats: StatsConfig,
/// How far behind its control plane this edge may fall before it reports
/// itself degraded.
#[serde(default)]
pub replication: ReplicationConfig,
/// DID of the control plane that drives this edge — the one party whose
/// signed Trust Tasks it applies. Required: the server does not start
/// without it.
pub control_did: Option<String>,
#[serde(default)]
pub vta: VtaConfig,
/// How the service's own identity is produced, and how long a superseded
/// generation keeps being honoured after a rotation
/// (`identity.rotation_grace_period`).
#[serde(default)]
pub identity: did_hosting_common::server::config::IdentityConfig,
#[serde(skip)]
pub config_path: PathBuf,
}
/// The replication staleness bound.
///
/// The control plane delivers every change through its outbox and retries
/// until this edge acknowledges it. As a backstop for anything that still goes
/// missing — an outbox entry dropped past its retry budget, a push lost while
/// the edge was down — the edge reconciles against the control plane's
/// `did-management/did/list` every `reconcile_interval_secs`, repairing a
/// missed disable on the spot and asking for a resync of anything else. When it
/// has not completed a clean reconcile within `staleness_bound_secs`, its
/// `/api/health` probe answers `503`, so a load balancer drains it instead of
/// letting it serve state that may be out of date.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ReplicationConfig {
/// The longest an edge may go without a clean reconcile and still report
/// healthy. Default 300 (5 minutes).
#[serde(default = "default_staleness_bound_secs")]
pub staleness_bound_secs: u64,
/// How often the edge reconciles. Must be shorter than the bound, so a
/// single missed round does not trip it. Default 60.
#[serde(default = "default_reconcile_interval_secs")]
pub reconcile_interval_secs: u64,
}
fn default_staleness_bound_secs() -> u64 {
300
}
fn default_reconcile_interval_secs() -> u64 {
60
}
impl Default for ReplicationConfig {
fn default() -> Self {
Self {
staleness_bound_secs: default_staleness_bound_secs(),
reconcile_interval_secs: default_reconcile_interval_secs(),
}
}
}
impl ReplicationConfig {
/// Refuse a bound the reconcile interval cannot keep.
pub fn validate(&self) -> Result<(), AppError> {
if self.reconcile_interval_secs == 0 {
return Err(AppError::Config(
"replication.reconcile_interval_secs must be at least 1".into(),
));
}
if self.staleness_bound_secs <= self.reconcile_interval_secs {
return Err(AppError::Config(format!(
"replication.staleness_bound_secs ({}) must be longer than \
replication.reconcile_interval_secs ({})",
self.staleness_bound_secs, self.reconcile_interval_secs
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LimitsConfig {
/// Maximum body size (bytes) for did.jsonl / witness uploads. Default: 100KB.
#[serde(default = "default_upload_body_limit")]
pub upload_body_limit: usize,
/// Default per-account total DID document size (bytes). Default: 1MB.
#[serde(default = "default_max_total_size")]
pub default_max_total_size: u64,
/// Default per-account maximum number of DIDs. Default: 20.
#[serde(default = "default_max_did_count")]
pub default_max_did_count: u64,
}
fn default_upload_body_limit() -> usize {
102_400
}
fn default_max_total_size() -> u64 {
1_048_576
}
fn default_max_did_count() -> u64 {
20
}
impl Default for LimitsConfig {
fn default() -> Self {
Self {
upload_body_limit: default_upload_body_limit(),
default_max_total_size: default_max_total_size(),
default_max_did_count: default_max_did_count(),
}
}
}
/// Stats collection and sync configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StatsConfig {
/// How often (seconds) to flush in-memory counters to storage. Default: 5.
#[serde(default = "default_stats_flush_interval")]
pub flush_interval_secs: u64,
/// How often (seconds) to push aggregate stats to the control plane. Default: 1.
/// Set to 0 to disable sync.
#[serde(default = "default_stats_sync_interval")]
pub sync_interval_secs: u64,
}
fn default_stats_flush_interval() -> u64 {
5
}
fn default_stats_sync_interval() -> u64 {
1
}
impl Default for StatsConfig {
fn default() -> Self {
Self {
flush_interval_secs: default_stats_flush_interval(),
sync_interval_secs: default_stats_sync_interval(),
}
}
}
impl AppConfig {
/// Return the public-facing base URL for this server.
pub fn public_base_url(&self) -> String {
self.public_url
.clone()
.unwrap_or_else(|| format!("http://{}:{}", self.server.host, self.server.port))
}
pub fn load(config_path: Option<PathBuf>) -> Result<Self, AppError> {
let path = config_path
.or_else(|| {
std::env::var("DID_HOSTING_CONFIG_PATH")
.ok()
.map(PathBuf::from)
})
.unwrap_or_else(|| PathBuf::from("config.toml"));
if !path.exists() {
return Err(AppError::Config(format!(
"configuration file not found: {}",
path.display()
)));
}
let contents = std::fs::read_to_string(&path).map_err(AppError::Io)?;
let mut config = toml::from_str::<AppConfig>(&contents)
.map_err(|e| AppError::Config(format!("failed to parse {}: {e}", path.display())))?;
config.config_path = path.clone();
// Shared env overrides (features, server, log, store, auth, secrets).
// `DID_HOSTING_` is the documented prefix. `WEBVH_` is what these were
// read under before, applied first so a set `DID_HOSTING_` name wins.
// Deprecated: drop it once deployments have moved.
for prefix in ["WEBVH", "DID_HOSTING"] {
did_hosting_common::server::config::apply_env_overrides(
prefix,
&mut config.features,
&mut config.server,
&mut config.log,
&mut config.store,
&mut config.auth,
&mut config.secrets,
)?;
}
// Fjall memory settings (STORAGE_FJALL_BLOCK_CACHE / _WRITE_BUFFER /
// _MAX_JOURNAL) — shared, unprefixed names; see
// `did_hosting_common::server::config::apply_fjall_env_overrides`.
did_hosting_common::server::config::apply_fjall_env_overrides(&mut config.fjall)?;
// Server identity (did-hosting-server specific env vars)
macro_rules! env_opt {
($var:expr, $field:expr) => {
if let Ok(v) = std::env::var($var) {
$field = Some(v);
}
};
}
macro_rules! env_parse {
($var:expr, $field:expr) => {
if let Ok(v) = std::env::var($var) {
$field = v
.parse()
.map_err(|e| AppError::Config(format!("invalid {}: {e}", $var)))?;
}
};
}
env_opt!("DID_HOSTING_SERVER_DID", config.server_did);
env_opt!("DID_HOSTING_MEDIATOR_DID", config.mediator_did);
env_opt!("DID_HOSTING_PUBLIC_URL", config.public_url);
env_opt!("DID_HOSTING_CONTROL_DID", config.control_did);
// VTA config
env_opt!("DID_HOSTING_VTA_URL", config.vta.url);
env_opt!("DID_HOSTING_VTA_DID", config.vta.did);
env_opt!("DID_HOSTING_VTA_CONTEXT_ID", config.vta.context_id);
// Limits
env_parse!(
"DID_HOSTING_REPLICATION_STALENESS_BOUND_SECS",
config.replication.staleness_bound_secs
);
env_parse!(
"DID_HOSTING_REPLICATION_RECONCILE_INTERVAL_SECS",
config.replication.reconcile_interval_secs
);
env_parse!(
"DID_HOSTING_LIMITS_UPLOAD_BODY_LIMIT",
config.limits.upload_body_limit
);
env_parse!(
"DID_HOSTING_LIMITS_DEFAULT_MAX_TOTAL_SIZE",
config.limits.default_max_total_size
);
env_parse!(
"DID_HOSTING_LIMITS_DEFAULT_MAX_DID_COUNT",
config.limits.default_max_did_count
);
// Stats
env_parse!(
"DID_HOSTING_STATS_FLUSH_INTERVAL_SECS",
config.stats.flush_interval_secs
);
env_parse!(
"DID_HOSTING_STATS_SYNC_INTERVAL_SECS",
config.stats.sync_interval_secs
);
// DID_HOSTING_SERVER_RESOLVE_CACHE_* — Cache-Control on DID
// resolution. Also validates `[server.resolve_cache]`.
config
.server
.resolve_cache
.apply_env_overrides("DID_HOSTING")?;
// Validate configuration
config.auth.validate()?;
if let Some(ref did) = config.server_did
&& !did.starts_with("did:")
{
return Err(AppError::Config(format!(
"server_did must start with 'did:': {did}"
)));
}
if let Some(ref url) = config.public_url
&& !url.starts_with("http://")
&& !url.starts_with("https://")
{
return Err(AppError::Config(format!(
"public_url must start with http:// or https://: {url}"
)));
}
// Normalize: strip trailing slashes from URLs
if let Some(ref mut url) = config.public_url {
let trimmed = url.trim_end_matches('/').to_string();
*url = trimmed;
}
Ok(config)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The documented `DID_HOSTING_` names reach the shared settings, the
/// legacy `WEBVH_` names still work, and the documented name wins.
#[test]
fn shared_env_overrides_read_did_hosting_then_legacy_webvh() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "").unwrap();
// SAFETY: no other test in this crate loads config or reads these
// names, so nothing races these writes.
unsafe {
std::env::set_var("DID_HOSTING_SERVER_PORT", "9999");
std::env::set_var("WEBVH_LOG_LEVEL", "warn");
}
let config = AppConfig::load(Some(path.clone())).unwrap();
assert_eq!(config.server.port, 9999, "documented name applies");
assert_eq!(config.log.level, "warn", "legacy name still applies");
unsafe { std::env::set_var("DID_HOSTING_LOG_LEVEL", "debug") };
let config = AppConfig::load(Some(path)).unwrap();
assert_eq!(config.log.level, "debug", "documented name wins");
unsafe {
std::env::remove_var("DID_HOSTING_SERVER_PORT");
std::env::remove_var("WEBVH_LOG_LEVEL");
std::env::remove_var("DID_HOSTING_LOG_LEVEL");
}
}
}