zerodds-websocket-bridge 1.0.0-rc.1

WebSocket (RFC 6455) komplettes Stack-Set: Base-Framing + Handshake + permessage-deflate (RFC 7692) + URI + UTF-8-Validator + DDS-Bridge — no_std + alloc.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors

//! Config-File-Parser fuer `zerodds-ws-bridged`.
//!
//! Spec: `zerodds-ws-bridge-1.0.md` §3.
//!
//! YAML-Subset (kein externer Parser im Workspace):
//!
//! * Top-Level Mapping (Schluessel-Wert).
//! * Verschachtelte Mappings via Indent (2 Spaces).
//! * Sequenzen via `- ` Prefix mit Indent.
//! * Skalare: Strings (mit/ohne Quotes), Integer, Bool (`true`/`false`).
//! * `#` Kommentare bis EOL.
//! * `${VAR}` und `${VAR:-default}` ENV-Substitution vor dem Parse.
//!
//! Bewusst kein generischer YAML-Parser — der Spec-Subset ist
//! explizit; alles ausserhalb wird mit `ConfigError::Syntax` lehnt
//! abgelehnt.

use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::path::Path;
use std::string::{String, ToString};
use std::vec::Vec;

/// Geparste Daemon-Config.
#[derive(Debug, Clone, Default)]
pub struct DaemonConfig {
    /// `listen: <addr>` — Bind-Address.
    pub listen: String,
    /// `domain: <id>` — DDS-Domain-ID.
    pub domain: i32,
    /// `log_level: <level>`.
    pub log_level: String,
    /// `topics:` Liste.
    pub topics: Vec<TopicConfig>,
    /// `tls.enabled` — wenn true, müssen `tls_cert_file`+`tls_key_file`
    /// gesetzt sein. Spec §7.1.
    pub tls_enabled: bool,
    /// `tls.cert_file` — PEM-Cert-Pfad.
    pub tls_cert_file: String,
    /// `tls.key_file` — PEM-Key-Pfad.
    pub tls_key_file: String,
    /// `tls.client_ca_file` — PEM-CA-Bundle für mTLS Client-Auth.
    pub tls_client_ca_file: String,
    /// `auth.mode` — `none|bearer|jwt|mtls|sasl`. Spec §7.2.
    pub auth_mode: String,
    /// `auth.bearer_token` — Single-Token-Form (Map mit einem Eintrag).
    pub auth_bearer_token: Option<String>,
    /// `auth.bearer_token_subject` — wer hinter dem Bearer steckt.
    pub auth_bearer_subject: Option<String>,
    /// Topic-ACL: `topic → ("read,write" CSV von Subjects)`. Spec §7.3.
    pub topic_acl: std::collections::HashMap<String, (Vec<String>, Vec<String>)>,
    /// `metrics.enabled` — schaltet den Prometheus-Endpoint (§8.2).
    pub metrics_enabled: bool,
    /// Bind-Address fuer Admin-Endpoint (`/metrics`, `/catalog`,
    /// `/healthz`). Wenn leer aber `metrics_enabled=true`: default
    /// `127.0.0.1:9090`. Per CLI/`metrics.address` ueberschreibbar.
    pub metrics_addr: String,
}

/// Single Topic-Map-Entry.
#[derive(Debug, Clone, Default)]
pub struct TopicConfig {
    /// `name:` — DDS-Topic-Name.
    pub name: String,
    /// `type:` — DDS-Type-Name.
    pub type_name: String,
    /// `direction:` — `in|out|bidir`.
    pub direction: String,
    /// `ws_path:` — Override-URL-Pfad.
    pub ws_path: String,
    /// `qos.reliability:`.
    pub reliability: String,
    /// `qos.durability:`.
    pub durability: String,
    /// `qos.history.depth:`.
    pub history_depth: i32,
}

/// Config-Fehler.
#[derive(Debug, Clone)]
pub enum ConfigError {
    /// File-IO-Fehler.
    Io(String),
    /// YAML-Syntax-Fehler.
    Syntax(String),
    /// Pflicht-Feld fehlt.
    MissingField(String),
    /// Wert-Typ unpassend.
    BadValue {
        /// Feldname.
        field: String,
        /// Roher Wert.
        value: String,
    },
}

impl core::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Io(m) => write!(f, "config io: {m}"),
            Self::Syntax(m) => write!(f, "config syntax: {m}"),
            Self::MissingField(m) => write!(f, "config missing field: {m}"),
            Self::BadValue { field, value } => {
                write!(f, "config bad value for {field}: {value}")
            }
        }
    }
}

impl std::error::Error for ConfigError {}

impl DaemonConfig {
    /// Default-Config (wenn weder File noch CLI-Override gesetzt sind).
    #[must_use]
    pub fn default_for_dev() -> Self {
        Self {
            listen: "127.0.0.1:8080".to_string(),
            domain: 0,
            log_level: "info".to_string(),
            topics: Vec::new(),
            tls_enabled: false,
            tls_cert_file: String::new(),
            tls_key_file: String::new(),
            tls_client_ca_file: String::new(),
            auth_mode: "none".to_string(),
            auth_bearer_token: None,
            auth_bearer_subject: None,
            topic_acl: std::collections::HashMap::new(),
            metrics_enabled: false,
            metrics_addr: String::new(),
        }
    }

    /// Laedt + parst eine Config aus File.
    ///
    /// # Errors
    /// `Io` bei Read-Fehler, `Syntax`/`MissingField`/`BadValue` bei
    /// fehlerhaftem YAML.
    pub fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
        let raw = fs::read_to_string(path).map_err(|e| ConfigError::Io(e.to_string()))?;
        Self::load_from_str(&raw)
    }

    /// Parst Config aus YAML-String. Public fuer Tests.
    ///
    /// # Errors
    /// Siehe [`ConfigError`].
    pub fn load_from_str(raw: &str) -> Result<Self, ConfigError> {
        let expanded = expand_env_vars(raw);
        let nodes = parse_yaml_subset(&expanded)?;
        let mut out = Self::default_for_dev();
        for (k, v) in nodes.iter() {
            match k.as_str() {
                "listen" => out.listen = v.as_scalar()?,
                "domain" => {
                    let s = v.as_scalar()?;
                    out.domain = s.parse().map_err(|_| ConfigError::BadValue {
                        field: "domain".to_string(),
                        value: s,
                    })?;
                }
                "log_level" => out.log_level = v.as_scalar()?,
                "tls" => {
                    if let YamlNode::Map(m) = v {
                        if let Some(YamlNode::Scalar(s)) = m.get("enabled") {
                            out.tls_enabled = parse_bool(s);
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("cert_file") {
                            out.tls_cert_file = s.clone();
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("key_file") {
                            out.tls_key_file = s.clone();
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("client_ca_file") {
                            out.tls_client_ca_file = s.clone();
                        }
                    }
                }
                "auth" => {
                    if let YamlNode::Map(m) = v {
                        if let Some(YamlNode::Scalar(s)) = m.get("mode") {
                            out.auth_mode = s.clone();
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("bearer_token") {
                            out.auth_bearer_token = Some(s.clone());
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("bearer_subject") {
                            out.auth_bearer_subject = Some(s.clone());
                        }
                    }
                }
                "acl" => {
                    if let YamlNode::Map(m) = v {
                        for (topic, entry) in m.iter() {
                            if let YamlNode::Map(em) = entry {
                                let read = em
                                    .get("read")
                                    .and_then(|n| match n {
                                        YamlNode::Scalar(s) => Some(
                                            s.split(',').map(|x| x.trim().to_string()).collect(),
                                        ),
                                        _ => None,
                                    })
                                    .unwrap_or_default();
                                let write = em
                                    .get("write")
                                    .and_then(|n| match n {
                                        YamlNode::Scalar(s) => Some(
                                            s.split(',').map(|x| x.trim().to_string()).collect(),
                                        ),
                                        _ => None,
                                    })
                                    .unwrap_or_default();
                                out.topic_acl.insert(topic.clone(), (read, write));
                            }
                        }
                    }
                }
                "metrics" => {
                    if let YamlNode::Map(m) = v {
                        if let Some(YamlNode::Scalar(s)) = m.get("enabled") {
                            out.metrics_enabled = parse_bool(s);
                        }
                        if let Some(YamlNode::Scalar(s)) = m.get("address") {
                            out.metrics_addr = s.clone();
                        }
                    }
                }
                "topics" => {
                    if let YamlNode::Seq(items) = v {
                        for item in items.iter() {
                            if let YamlNode::Map(m) = item {
                                let mut t = TopicConfig::default();
                                if let Some(YamlNode::Scalar(s)) = m.get("name") {
                                    t.name = s.clone();
                                }
                                if let Some(YamlNode::Scalar(s)) = m.get("type") {
                                    t.type_name = s.clone();
                                }
                                if let Some(YamlNode::Scalar(s)) = m.get("direction") {
                                    t.direction = s.clone();
                                } else {
                                    t.direction = "bidir".to_string();
                                }
                                if let Some(YamlNode::Scalar(s)) = m.get("ws_path") {
                                    t.ws_path = s.clone();
                                }
                                if let Some(YamlNode::Map(qm)) = m.get("qos") {
                                    if let Some(YamlNode::Scalar(s)) = qm.get("reliability") {
                                        t.reliability = s.clone();
                                    }
                                    if let Some(YamlNode::Scalar(s)) = qm.get("durability") {
                                        t.durability = s.clone();
                                    }
                                    if let Some(YamlNode::Map(hm)) = qm.get("history") {
                                        if let Some(YamlNode::Scalar(s)) = hm.get("depth") {
                                            t.history_depth = s.parse().unwrap_or(10);
                                        }
                                    }
                                }
                                if t.name.is_empty() {
                                    return Err(ConfigError::MissingField(
                                        "topics[].name".to_string(),
                                    ));
                                }
                                if t.type_name.is_empty() {
                                    t.type_name = t.name.clone();
                                }
                                if t.ws_path.is_empty() {
                                    t.ws_path = default_ws_path(&t.name);
                                }
                                out.topics.push(t);
                            }
                        }
                    }
                }
                _ => {} // unbekannte top-level-keys werden ignoriert
            }
        }
        Ok(out)
    }
}

/// Slug-Algorithmus per Spec §5.1: `Chat::Message` → `/topics/chat/message`.
#[must_use]
pub fn default_ws_path(topic: &str) -> String {
    let mut buf = String::from("/topics/");
    let lower = topic.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if i + 1 < bytes.len() && bytes[i] == b':' && bytes[i + 1] == b':' {
            buf.push('/');
            i += 2;
            continue;
        }
        let c = bytes[i] as char;
        if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '/' {
            buf.push(c);
        } else {
            buf.push('_');
        }
        i += 1;
    }
    buf
}

fn parse_bool(s: &str) -> bool {
    matches!(s.trim().to_ascii_lowercase().as_str(), "true" | "yes" | "1")
}

/// `${VAR}` und `${VAR:-default}` Substitution.
#[must_use]
pub fn expand_env_vars(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let chars: Vec<char> = input.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if i + 1 < chars.len() && chars[i] == '$' && chars[i + 1] == '{' {
            // Find closing `}`.
            if let Some(end) = chars[i + 2..].iter().position(|&c| c == '}') {
                let inner: String = chars[i + 2..i + 2 + end].iter().collect();
                let (name, default) = match inner.split_once(":-") {
                    Some((n, d)) => (n.to_string(), Some(d.to_string())),
                    None => (inner.clone(), None),
                };
                let value = env::var(&name).ok().or(default).unwrap_or_default();
                out.push_str(&value);
                i += 2 + end + 1;
                continue;
            }
        }
        out.push(chars[i]);
        i += 1;
    }
    out
}

/// YAML-Subset-AST.
#[derive(Debug, Clone)]
enum YamlNode {
    Scalar(String),
    Seq(Vec<YamlNode>),
    Map(BTreeMap<String, YamlNode>),
}

impl YamlNode {
    fn as_scalar(&self) -> Result<String, ConfigError> {
        match self {
            Self::Scalar(s) => Ok(s.clone()),
            _ => Err(ConfigError::Syntax("expected scalar".to_string())),
        }
    }
}

/// Mini-YAML-Parser. Verarbeitet nur das Spec-Subset.
fn parse_yaml_subset(raw: &str) -> Result<BTreeMap<String, YamlNode>, ConfigError> {
    // Tokenize: pro Zeile `(indent, content)`.
    let mut lines: Vec<(usize, String)> = Vec::new();
    for line in raw.split('\n') {
        // Strip `#`-Kommentare (ausserhalb von Quotes).
        let stripped = strip_comment(line);
        if stripped.trim().is_empty() {
            continue;
        }
        let indent = stripped.chars().take_while(|c| *c == ' ').count();
        let content = stripped[indent..].to_string();
        lines.push((indent, content));
    }
    let (out, _) = parse_block_map(&lines, 0, 0)?;
    Ok(out)
}

fn strip_comment(line: &str) -> String {
    let mut out = String::new();
    let mut in_quote: Option<char> = None;
    for c in line.chars() {
        match in_quote {
            Some(q) => {
                out.push(c);
                if c == q {
                    in_quote = None;
                }
            }
            None => {
                if c == '#' {
                    break;
                }
                if c == '"' || c == '\'' {
                    in_quote = Some(c);
                }
                out.push(c);
            }
        }
    }
    // Trim trailing whitespace.
    out.trim_end().to_string()
}
/// zerodds-lint: recursion-depth 64 (parse_block_map bounded by AST depth)
fn parse_block_map(
    lines: &[(usize, String)],
    start: usize,
    indent: usize,
) -> Result<(BTreeMap<String, YamlNode>, usize), ConfigError> {
    let mut map = BTreeMap::new();
    let mut i = start;
    while i < lines.len() {
        let (line_indent, content) = &lines[i];
        if *line_indent < indent {
            break;
        }
        if *line_indent > indent {
            return Err(ConfigError::Syntax(alloc_format(format_args!(
                "unexpected indent at line containing {content}"
            ))));
        }
        if content.starts_with("- ") || content.as_str() == "-" {
            // We are inside a map but encountered a sequence-marker.
            return Err(ConfigError::Syntax(
                "unexpected sequence marker in map context".to_string(),
            ));
        }
        let (key, value) = match content.split_once(':') {
            Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
            None => {
                return Err(ConfigError::Syntax(alloc_format(format_args!(
                    "no `:` in line: {content}"
                ))));
            }
        };
        if !value.is_empty() {
            // Inline scalar.
            map.insert(key, YamlNode::Scalar(unquote(&value)));
            i += 1;
        } else {
            // Block-Child auf next-deeper Indent.
            i += 1;
            // Naechste nicht-leere Line bestimmt das Format.
            if i >= lines.len() || lines[i].0 <= indent {
                // leere Body — als leerer Scalar.
                map.insert(key, YamlNode::Scalar(String::new()));
                continue;
            }
            let child_indent = lines[i].0;
            let child_content = &lines[i].1;
            if child_content.starts_with("- ") || child_content.as_str() == "-" {
                let (seq, advanced) = parse_block_seq(lines, i, child_indent)?;
                map.insert(key, YamlNode::Seq(seq));
                i = advanced;
            } else {
                let (sub, advanced) = parse_block_map(lines, i, child_indent)?;
                map.insert(key, YamlNode::Map(sub));
                i = advanced;
            }
        }
    }
    Ok((map, i))
}
/// zerodds-lint: recursion-depth 64 (parse_block_seq bounded by AST depth)
fn parse_block_seq(
    lines: &[(usize, String)],
    start: usize,
    indent: usize,
) -> Result<(Vec<YamlNode>, usize), ConfigError> {
    let mut seq = Vec::new();
    let mut i = start;
    while i < lines.len() {
        let (line_indent, content) = &lines[i];
        if *line_indent < indent {
            break;
        }
        if *line_indent > indent {
            return Err(ConfigError::Syntax("seq misindented".to_string()));
        }
        if !content.starts_with('-') {
            break;
        }
        // `- key: value`-Form vs `-` block child auf naechster Zeile
        let after_dash = if content == "-" {
            String::new()
        } else if content.starts_with("- ") {
            content[2..].to_string()
        } else {
            return Err(ConfigError::Syntax("malformed seq item".to_string()));
        };
        if after_dash.is_empty() {
            // Item-Body auf naechster Zeile.
            i += 1;
            if i >= lines.len() || lines[i].0 <= indent {
                seq.push(YamlNode::Scalar(String::new()));
                continue;
            }
            let child_indent = lines[i].0;
            let (sub, advanced) = parse_block_map(lines, i, child_indent)?;
            seq.push(YamlNode::Map(sub));
            i = advanced;
        } else if let Some((k, v)) = after_dash.split_once(':') {
            let k = k.trim().to_string();
            let v = v.trim();
            // Sammle: erster Eintrag inline + Folge-Lines mit `child_indent =
            // indent + 2` als Map-Members.
            let mut sub = BTreeMap::new();
            if v.is_empty() {
                // Block-Child fuer ersten Key auf naechster Zeile.
                i += 1;
                if i >= lines.len() {
                    sub.insert(k, YamlNode::Scalar(String::new()));
                } else if lines[i].0 > indent + 2 {
                    let ci = lines[i].0;
                    let child = &lines[i].1;
                    if child.starts_with("- ") || child == "-" {
                        let (s2, advanced) = parse_block_seq(lines, i, ci)?;
                        sub.insert(k, YamlNode::Seq(s2));
                        i = advanced;
                    } else {
                        let (m2, advanced) = parse_block_map(lines, i, ci)?;
                        sub.insert(k, YamlNode::Map(m2));
                        i = advanced;
                    }
                } else {
                    sub.insert(k, YamlNode::Scalar(String::new()));
                }
            } else {
                sub.insert(k, YamlNode::Scalar(unquote(v)));
                i += 1;
            }
            // Sammle weitere Mitglieder dieses Map-Items: indent muss
            // > seq-indent sein, exakt = indent + 2.
            let item_member_indent = indent + 2;
            while i < lines.len() {
                let (li, lc) = &lines[i];
                if *li < item_member_indent {
                    break;
                }
                if *li == indent && (lc.starts_with("- ") || lc == "-") {
                    break;
                }
                if *li != item_member_indent {
                    break;
                }
                if lc.starts_with("- ") {
                    break;
                }
                let (kk, vv) = lc
                    .split_once(':')
                    .ok_or_else(|| ConfigError::Syntax("seq map missing colon".to_string()))?;
                let kk = kk.trim().to_string();
                let vv = vv.trim();
                if vv.is_empty() {
                    i += 1;
                    if i < lines.len() && lines[i].0 > item_member_indent {
                        let ci = lines[i].0;
                        let child = &lines[i].1;
                        if child.starts_with("- ") || child == "-" {
                            let (s2, advanced) = parse_block_seq(lines, i, ci)?;
                            sub.insert(kk, YamlNode::Seq(s2));
                            i = advanced;
                        } else {
                            let (m2, advanced) = parse_block_map(lines, i, ci)?;
                            sub.insert(kk, YamlNode::Map(m2));
                            i = advanced;
                        }
                    } else {
                        sub.insert(kk, YamlNode::Scalar(String::new()));
                    }
                } else {
                    sub.insert(kk, YamlNode::Scalar(unquote(vv)));
                    i += 1;
                }
            }
            seq.push(YamlNode::Map(sub));
        } else {
            // Inline-Scalar.
            seq.push(YamlNode::Scalar(unquote(&after_dash)));
            i += 1;
        }
    }
    Ok((seq, i))
}

fn unquote(v: &str) -> String {
    let v = v.trim();
    if (v.starts_with('"') && v.ends_with('"') && v.len() >= 2)
        || (v.starts_with('\'') && v.ends_with('\'') && v.len() >= 2)
    {
        v[1..v.len() - 1].to_string()
    } else {
        v.to_string()
    }
}

fn alloc_format(args: core::fmt::Arguments<'_>) -> String {
    use core::fmt::Write as _;
    let mut s = String::new();
    let _ = s.write_fmt(args);
    s
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn slug_strips_double_colon() {
        assert_eq!(default_ws_path("Chat::Message"), "/topics/chat/message");
    }

    #[test]
    fn slug_replaces_unsafe_chars() {
        assert_eq!(default_ws_path("My Topic!"), "/topics/my_topic_");
    }

    #[test]
    fn env_substitution_with_default() {
        // Test mit einem garantiert nicht gesetzten Var-Namen
        // (UUID-Style, damit wir nicht auf process-state vertrauen).
        let s = expand_env_vars("token: ${ZERODDS_PROBABLY_UNSET_VAR_e2afb0b9_test:-fallback}");
        assert!(s.contains("fallback"), "got: {s}");
    }

    #[test]
    fn env_substitution_passthrough_when_no_placeholder() {
        let s = expand_env_vars("plain: value");
        assert_eq!(s, "plain: value");
    }

    #[test]
    fn parse_minimal_config() {
        let yaml = "\
listen: \"0.0.0.0:8080\"
domain: 0
log_level: info
topics:
  - name: \"Chat::Message\"
    type: \"Chat::Message\"
    direction: bidir
";
        let cfg = DaemonConfig::load_from_str(yaml).unwrap();
        assert_eq!(cfg.listen, "0.0.0.0:8080");
        assert_eq!(cfg.domain, 0);
        assert_eq!(cfg.topics.len(), 1);
        assert_eq!(cfg.topics[0].name, "Chat::Message");
        assert_eq!(cfg.topics[0].direction, "bidir");
        assert_eq!(cfg.topics[0].ws_path, "/topics/chat/message");
    }

    #[test]
    fn parse_qos_block() {
        let yaml = "\
listen: 0.0.0.0:8080
domain: 0
topics:
  - name: T
    qos:
      reliability: reliable
      durability: volatile
      history:
        depth: 25
";
        let cfg = DaemonConfig::load_from_str(yaml).unwrap();
        assert_eq!(cfg.topics[0].reliability, "reliable");
        assert_eq!(cfg.topics[0].durability, "volatile");
        assert_eq!(cfg.topics[0].history_depth, 25);
    }

    #[test]
    fn parse_tls_and_auth_blocks() {
        let yaml = "\
listen: 0.0.0.0:8080
domain: 0
tls:
  enabled: true
auth:
  mode: bearer
  bearer_token: secret
metrics:
  enabled: true
topics:
  - name: T
";
        let cfg = DaemonConfig::load_from_str(yaml).unwrap();
        assert!(cfg.tls_enabled);
        assert_eq!(cfg.auth_mode, "bearer");
        assert_eq!(cfg.auth_bearer_token.as_deref(), Some("secret"));
        assert!(cfg.metrics_enabled);
    }

    #[test]
    fn parse_rejects_bad_domain() {
        let yaml = "\
listen: x
domain: notanint
";
        let err = DaemonConfig::load_from_str(yaml).unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }
}