zerodds-security 1.0.0-rc.1

DDS-Security 1.1 Plugin-SPI fuer ZeroDDS: Authentication / AccessControl / Cryptographic / Logging / DataTagging Trait-Definitionen + Generic-Message-Topics + Token-Datenmodell.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors

//! DDS-Security 1.2 Token-Strukturen (DataHolder + Property-Records).
//!
//! Spec: §7.2.6 (Property_t / BinaryProperty_t), §7.2.7 (DataHolder),
//! §7.4.1.4 (IdentityToken im SPDP-Announce).
//!
//! Ein **DataHolder** ist die generische Wire-Repraesentation aller
//! Security-Tokens (IdentityToken, PermissionsToken, IdentityStatus-
//! Token, AuthRequestMessageToken, HandshakeMessageToken, CryptoToken,
//! ParticipantCryptoToken etc.). Felder:
//!
//! ```text
//! struct DataHolder_t {
//!     string                       class_id;
//!     sequence<Property_t>         properties;
//!     sequence<BinaryProperty_t>   binary_properties;
//! };
//! struct Property_t        { string name; string value; };
//! struct BinaryProperty_t  { string name; sequence<octet> value; };
//! ```
//!
//! WICHTIG: das Wire-`Property_t` (Spec §7.2.6 Tab.5) hat **kein**
//! `propagate`-Feld — das ist Local-Filter-State im plug-konfigurierten
//! `zerodds_security::PropertyList`.
//!
//! Encoding ist OMG-CDR (XCDR1) — der DataHolder wird als Big-/Little-
//! Endian Stream serialisiert, je nachdem in welchem Encapsulation-
//! Kontext er sitzt (typisch PL_CDR_LE der ParameterList, also LE).
//!
//! # Verwendung
//!
//! ```
//! use zerodds_security::token::{DataHolder, IdentityToken};
//! let tok = IdentityToken::pki_dh_v12("01:23:45", "rsa-2048", "FA:CE", "rsa-2048");
//! let bytes = tok.to_cdr_le();
//! let back = DataHolder::from_cdr_le(&bytes).unwrap();
//! assert_eq!(tok, back);
//! ```

extern crate alloc;

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::error::{SecurityError, SecurityErrorKind, SecurityResult};

/// Spec §7.2.6 Tab.5 — Wire-`Property_t` (`name` + `value`, beide
/// CDR-Strings). Im Gegensatz zu [`crate::Property`] kein `propagate`-
/// Feld; Token-Properties werden grundsaetzlich propagiert.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WireProperty {
    /// Property-Name (reverse-DNS, z.B. `"dds.cert.sn"`).
    pub name: String,
    /// Property-Value (UTF-8).
    pub value: String,
}

impl WireProperty {
    /// Konstruktor.
    #[must_use]
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }
}

/// Spec §7.2.6 Tab.6 — Wire-`BinaryProperty_t` (`name` + `value` als
/// `sequence<octet>`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct BinaryProperty {
    /// Property-Name (reverse-DNS).
    pub name: String,
    /// Roher Byte-Wert.
    pub value: Vec<u8>,
}

impl BinaryProperty {
    /// Konstruktor.
    #[must_use]
    pub fn new(name: impl Into<String>, value: impl Into<Vec<u8>>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }
}

/// Spec §7.2.7 Tab.7 — generische `DataHolder_t` Wire-Struktur. Alle
/// Security-Tokens sind Type-Aliases von `DataHolder` mit fixem
/// `class_id`-Wert.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DataHolder {
    /// Plugin-Class-Id, z.B. `"DDS:Auth:PKI-DH:1.2"`.
    pub class_id: String,
    /// String-Properties (Spec §7.2.6 Tab.5).
    pub properties: Vec<WireProperty>,
    /// Binary-Properties (Spec §7.2.6 Tab.6).
    pub binary_properties: Vec<BinaryProperty>,
}

impl DataHolder {
    /// Konstruktor mit nur `class_id`.
    #[must_use]
    pub fn new(class_id: impl Into<String>) -> Self {
        Self {
            class_id: class_id.into(),
            properties: Vec::new(),
            binary_properties: Vec::new(),
        }
    }

    /// Builder: fuegt eine String-Property hinzu.
    #[must_use]
    pub fn with_property(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.properties.push(WireProperty::new(name, value));
        self
    }

    /// Builder: fuegt eine Binary-Property hinzu.
    #[must_use]
    pub fn with_binary_property(
        mut self,
        name: impl Into<String>,
        value: impl Into<Vec<u8>>,
    ) -> Self {
        self.binary_properties
            .push(BinaryProperty::new(name, value));
        self
    }

    /// Mut-Variante: setzt eine String-Property mit Replace-on-Dup-
    /// Semantik (wenn Name schon existiert, wird der alte Wert
    /// ueberschrieben — Spec §7.2.6: pro Token darf jeder Property-
    /// Name nur einmal vorkommen).
    pub fn set_property(&mut self, name: impl Into<String>, value: impl Into<String>) {
        let n = name.into();
        if let Some(existing) = self.properties.iter_mut().find(|p| p.name == n) {
            existing.value = value.into();
        } else {
            self.properties.push(WireProperty {
                name: n,
                value: value.into(),
            });
        }
    }

    /// Mut-Variante: setzt eine Binary-Property mit Replace-on-Dup.
    pub fn set_binary_property(&mut self, name: impl Into<String>, value: impl Into<Vec<u8>>) {
        let n = name.into();
        if let Some(existing) = self.binary_properties.iter_mut().find(|p| p.name == n) {
            existing.value = value.into();
        } else {
            self.binary_properties.push(BinaryProperty {
                name: n,
                value: value.into(),
            });
        }
    }

    /// Sucht eine String-Property nach Name.
    #[must_use]
    pub fn property(&self, name: &str) -> Option<&str> {
        self.properties
            .iter()
            .find(|p| p.name == name)
            .map(|p| p.value.as_str())
    }

    /// Sucht eine Binary-Property nach Name.
    #[must_use]
    pub fn binary_property(&self, name: &str) -> Option<&[u8]> {
        self.binary_properties
            .iter()
            .find(|p| p.name == name)
            .map(|p| p.value.as_slice())
    }

    /// XCDR1-Little-Endian-Encoder. Liefert die Bytes ohne
    /// Encapsulation-Header — der wird vom Caller (z.B. ParameterList-
    /// Wert) bereitgestellt.
    #[must_use]
    pub fn to_cdr_le(&self) -> Vec<u8> {
        encode(self, true)
    }

    /// XCDR1-Big-Endian-Encoder.
    #[must_use]
    pub fn to_cdr_be(&self) -> Vec<u8> {
        encode(self, false)
    }

    /// XCDR1-Decoder, Little-Endian.
    ///
    /// # Errors
    /// `BadArgument` wenn die Bytes nicht spec-konform sind (z.B.
    /// vorzeitiges Ende, zu lange Length-Prefixes).
    pub fn from_cdr_le(bytes: &[u8]) -> SecurityResult<Self> {
        decode(bytes, true)
    }

    /// XCDR1-Decoder, Big-Endian.
    ///
    /// # Errors
    /// `BadArgument` wenn die Bytes nicht spec-konform sind.
    pub fn from_cdr_be(bytes: &[u8]) -> SecurityResult<Self> {
        decode(bytes, false)
    }
}

// ---------------------------------------------------------------------
// Type-Aliases fuer die Token-Familien (Spec-Bezeichnung / class_id)
// ---------------------------------------------------------------------

/// IdentityToken (Spec §7.4.1.4 Tab.16; PKI-DH §10.3.2 Tab.51).
/// Wird im SPDP-Announce als `PID_IDENTITY_TOKEN` (0x1001) verschickt.
pub type IdentityToken = DataHolder;

/// PermissionsToken (Spec §7.4.1.5 Tab.17; PKI-Permissions §10.4.2
/// Tab.65). `PID_PERMISSIONS_TOKEN` (0x1002).
pub type PermissionsToken = DataHolder;

/// IdentityStatusToken (Spec §7.4.1.6, §10.3.2 Tab.53). `PID_IDENTITY_
/// STATUS_TOKEN` (0x1006). Traeger fuer OCSP-Live-Status.
pub type IdentityStatusToken = DataHolder;

/// PermissionsCredentialToken (Spec §10.4.2 Tab.64). Wird im
/// Stateless-Topic-Handshake transportiert, nicht im SPDP.
pub type PermissionsCredentialToken = DataHolder;

/// AuthRequestMessageToken (Spec §10.3.2 Tab.55).
pub type AuthRequestMessageToken = DataHolder;

/// HandshakeMessageToken — Request/Reply/Final (Spec §10.3.2 Tab.56-58).
pub type HandshakeMessageToken = DataHolder;

/// CryptoToken (Spec §10.5.2 Tab.72).
pub type CryptoToken = DataHolder;

// ---------------------------------------------------------------------
// Convenience-Konstruktoren fuer die typischen Token-Auspraegungen.
// ---------------------------------------------------------------------

/// Plugin-Class-Id-Konstanten — Spec-1.2-Versioniert (siehe C3.3).
pub mod class_id {
    /// Builtin-PKI-Authentication (§10.3.2.1 Tab.51).
    pub const AUTH_PKI_DH_V12: &str = "DDS:Auth:PKI-DH:1.2";
    /// Builtin-Permissions Access-Control (§10.4 Tab.69).
    pub const ACCESS_PERMISSIONS_V12: &str = "DDS:Access:Permissions:1.2";
    /// Builtin-AES-GCM-GMAC Crypto (§10.5 Tab.72).
    pub const CRYPTO_AES_GCM_GMAC_V12: &str = "DDS:Crypto:AES-GCM-GMAC:1.2";
    /// Permissions-Credential (§10.4.2 Tab.64).
    pub const ACCESS_PERMISSIONS_CREDENTIAL: &str = "DDS:Access:PermissionsCredential";
}

/// Property-Namen — Spec-1.2 (Auswahl).
pub mod prop {
    /// IdentityToken: Cert-Subject-Name-Serial. Spec §10.3.2.1 Tab.51.
    pub const CERT_SN: &str = "dds.cert.sn";
    /// IdentityToken: Cert-Signature-Algorithmus.
    pub const CERT_ALGO: &str = "dds.cert.algo";
    /// IdentityToken: CA-Subject-Name-Serial.
    pub const CA_SN: &str = "dds.ca.sn";
    /// IdentityToken: CA-Signature-Algorithmus.
    pub const CA_ALGO: &str = "dds.ca.algo";
    /// PermissionsToken: Permissions-CA-Subject-Name-Serial.
    /// Spec §10.4.2 Tab.65.
    pub const PERM_CA_SN: &str = "dds.perm_ca.sn";
    /// PermissionsToken: Permissions-CA-Signature-Algorithmus.
    pub const PERM_CA_ALGO: &str = "dds.perm_ca.algo";
}

impl IdentityToken {
    /// Builtin-Helfer fuer den PKI-DH-IdentityToken (§10.3.2.1 Tab.51).
    /// Properties `dds.cert.sn`, `dds.cert.algo`, `dds.ca.sn`,
    /// `dds.ca.algo`. Keine binary_properties.
    #[must_use]
    pub fn pki_dh_v12(
        cert_sn: impl Into<String>,
        cert_algo: impl Into<String>,
        ca_sn: impl Into<String>,
        ca_algo: impl Into<String>,
    ) -> Self {
        DataHolder::new(class_id::AUTH_PKI_DH_V12)
            .with_property(prop::CERT_SN, cert_sn)
            .with_property(prop::CERT_ALGO, cert_algo)
            .with_property(prop::CA_SN, ca_sn)
            .with_property(prop::CA_ALGO, ca_algo)
    }

    /// Builtin-Helfer fuer den Permissions-Token (§10.4.2 Tab.65).
    /// `class_id="DDS:Access:Permissions:1.2"`, properties
    /// `dds.perm_ca.sn` + `dds.perm_ca.algo`.
    #[must_use]
    pub fn permissions_v12(perm_ca_sn: impl Into<String>, perm_ca_algo: impl Into<String>) -> Self {
        DataHolder::new(class_id::ACCESS_PERMISSIONS_V12)
            .with_property(prop::PERM_CA_SN, perm_ca_sn)
            .with_property(prop::PERM_CA_ALGO, perm_ca_algo)
    }
}

// ---------------------------------------------------------------------
// XCDR1-Codec
// ---------------------------------------------------------------------
//
// Layout (LE oder BE, je nach `little_endian`):
//   string class_id              -- aligned 4
//   sequence<Property> props     -- aligned 4
//     uint32 count               -- 4 byte
//     N x { string name; string value; }  -- aligned 4 each
//   sequence<BinaryProperty> bp  -- aligned 4
//     uint32 count
//     N x { string name; sequence<octet> value; }  -- aligned 4 each
//
// CDR-String: uint32 length (incl. trailing \0) + UTF-8 bytes + \0 +
// padding to 4 byte. Length=0 ist erlaubt (= leerer String).

/// Maximale Zaehler/-Laengen die wir aus der Wire akzeptieren —
/// DoS-Cap. 64 KiB pro Token, 256 Properties, 256 Binary-Properties,
/// 8 KiB pro Property-Wert.
const MAX_TOKEN_BYTES: usize = 64 * 1024;
const MAX_PROPS: u32 = 256;
const MAX_BIN_PROPS: u32 = 256;
const MAX_STRING_LEN: u32 = 8 * 1024;
const MAX_BINARY_LEN: u32 = 8 * 1024;

fn encode(d: &DataHolder, le: bool) -> Vec<u8> {
    let mut out = Vec::with_capacity(64);
    encode_string(&mut out, &d.class_id, le);
    encode_u32(&mut out, d.properties.len() as u32, le);
    for p in &d.properties {
        encode_string(&mut out, &p.name, le);
        encode_string(&mut out, &p.value, le);
    }
    encode_u32(&mut out, d.binary_properties.len() as u32, le);
    for p in &d.binary_properties {
        encode_string(&mut out, &p.name, le);
        encode_octet_seq(&mut out, &p.value, le);
    }
    out
}

fn decode(bytes: &[u8], le: bool) -> SecurityResult<DataHolder> {
    if bytes.len() > MAX_TOKEN_BYTES {
        return Err(SecurityError::new(
            SecurityErrorKind::BadArgument,
            "token: payload exceeds DoS cap",
        ));
    }
    let mut cur = Cursor::new(bytes);
    let class_id = cur.read_string(le)?;
    let prop_count = cur.read_u32(le)?;
    if prop_count > MAX_PROPS {
        return Err(SecurityError::new(
            SecurityErrorKind::BadArgument,
            "token: property count exceeds cap",
        ));
    }
    let mut properties = Vec::with_capacity(prop_count as usize);
    for _ in 0..prop_count {
        let name = cur.read_string(le)?;
        let value = cur.read_string(le)?;
        properties.push(WireProperty { name, value });
    }
    let bin_count = cur.read_u32(le)?;
    if bin_count > MAX_BIN_PROPS {
        return Err(SecurityError::new(
            SecurityErrorKind::BadArgument,
            "token: binary_property count exceeds cap",
        ));
    }
    let mut binary_properties = Vec::with_capacity(bin_count as usize);
    for _ in 0..bin_count {
        let name = cur.read_string(le)?;
        let value = cur.read_octet_seq(le)?;
        binary_properties.push(BinaryProperty { name, value });
    }
    Ok(DataHolder {
        class_id,
        properties,
        binary_properties,
    })
}

fn align_to(out: &mut Vec<u8>, n: usize) {
    let pad = (n - out.len() % n) % n;
    for _ in 0..pad {
        out.push(0);
    }
}

fn encode_u32(out: &mut Vec<u8>, v: u32, le: bool) {
    align_to(out, 4);
    if le {
        out.extend_from_slice(&v.to_le_bytes());
    } else {
        out.extend_from_slice(&v.to_be_bytes());
    }
}

fn encode_string(out: &mut Vec<u8>, s: &str, le: bool) {
    let bytes = s.as_bytes();
    let len = (bytes.len() + 1) as u32;
    encode_u32(out, len, le);
    out.extend_from_slice(bytes);
    out.push(0);
}

fn encode_octet_seq(out: &mut Vec<u8>, v: &[u8], le: bool) {
    encode_u32(out, v.len() as u32, le);
    out.extend_from_slice(v);
}

struct Cursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    fn align_to(&mut self, n: usize) {
        let pad = (n - self.pos % n) % n;
        self.pos = self.pos.saturating_add(pad);
    }

    fn read_u32(&mut self, le: bool) -> SecurityResult<u32> {
        self.align_to(4);
        if self.pos + 4 > self.buf.len() {
            return Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: truncated u32",
            ));
        }
        let raw = [
            self.buf[self.pos],
            self.buf[self.pos + 1],
            self.buf[self.pos + 2],
            self.buf[self.pos + 3],
        ];
        self.pos += 4;
        Ok(if le {
            u32::from_le_bytes(raw)
        } else {
            u32::from_be_bytes(raw)
        })
    }

    fn read_string(&mut self, le: bool) -> SecurityResult<String> {
        let len = self.read_u32(le)?;
        if len > MAX_STRING_LEN {
            return Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: string exceeds cap",
            ));
        }
        if len == 0 {
            return Ok(String::new());
        }
        if self.pos + len as usize > self.buf.len() {
            return Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: truncated string",
            ));
        }
        let body = &self.buf[self.pos..self.pos + len as usize];
        self.pos += len as usize;
        // Spec: trailing NUL ist Pflicht; UTF-8 muss valide sein.
        if let Some((_, rest)) = body.split_last() {
            if body.last() != Some(&0) {
                return Err(SecurityError::new(
                    SecurityErrorKind::BadArgument,
                    "token: string missing trailing NUL",
                ));
            }
            let s = core::str::from_utf8(rest).map_err(|_| {
                SecurityError::new(SecurityErrorKind::BadArgument, "token: string not UTF-8")
            })?;
            Ok(s.to_string())
        } else {
            Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: zero-length string body",
            ))
        }
    }

    fn read_octet_seq(&mut self, le: bool) -> SecurityResult<Vec<u8>> {
        let len = self.read_u32(le)?;
        if len > MAX_BINARY_LEN {
            return Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: binary value exceeds cap",
            ));
        }
        if self.pos + len as usize > self.buf.len() {
            return Err(SecurityError::new(
                SecurityErrorKind::BadArgument,
                "token: truncated binary",
            ));
        }
        let v = self.buf[self.pos..self.pos + len as usize].to_vec();
        self.pos += len as usize;
        Ok(v)
    }
}

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

    #[test]
    fn empty_data_holder_roundtrip_le() {
        let dh = DataHolder::new("DDS:Auth:PKI-DH:1.2");
        let bytes = dh.to_cdr_le();
        let back = DataHolder::from_cdr_le(&bytes).unwrap();
        assert_eq!(dh, back);
    }

    #[test]
    fn empty_data_holder_roundtrip_be() {
        let dh = DataHolder::new("DDS:Auth:PKI-DH:1.2");
        let bytes = dh.to_cdr_be();
        let back = DataHolder::from_cdr_be(&bytes).unwrap();
        assert_eq!(dh, back);
    }

    #[test]
    fn pki_dh_identity_token_roundtrip() {
        let tok =
            IdentityToken::pki_dh_v12("01:23:45:67", "ECDSA-SHA256", "FA:CE:0B:01", "RSA-SHA256");
        let bytes = tok.to_cdr_le();
        let back = DataHolder::from_cdr_le(&bytes).unwrap();
        assert_eq!(tok, back);
        assert_eq!(back.class_id, "DDS:Auth:PKI-DH:1.2");
        assert_eq!(back.property("dds.cert.sn"), Some("01:23:45:67"));
        assert_eq!(back.property("dds.cert.algo"), Some("ECDSA-SHA256"));
        assert_eq!(back.property("dds.ca.sn"), Some("FA:CE:0B:01"));
        assert_eq!(back.property("dds.ca.algo"), Some("RSA-SHA256"));
        assert!(back.binary_properties.is_empty());
    }

    #[test]
    fn permissions_token_roundtrip() {
        let tok = IdentityToken::permissions_v12("DE:AD:BE:EF", "ECDSA-SHA256");
        let le = tok.to_cdr_le();
        let be = tok.to_cdr_be();
        assert_eq!(tok, DataHolder::from_cdr_le(&le).unwrap());
        assert_eq!(tok, DataHolder::from_cdr_be(&be).unwrap());
        assert_ne!(le, be, "BE/LE Streams unterscheiden sich");
    }

    #[test]
    fn token_with_binary_property_roundtrip() {
        let tok = DataHolder::new("DDS:Auth:PKI-DH:1.2")
            .with_property("dds.cert.sn", "01:23")
            .with_binary_property("dds.cert.bytes", vec![0xCA, 0xFE, 0xBA, 0xBE, 0xDE]);
        let bytes = tok.to_cdr_le();
        let back = DataHolder::from_cdr_le(&bytes).unwrap();
        assert_eq!(tok, back);
        assert_eq!(
            back.binary_property("dds.cert.bytes"),
            Some(&[0xCA, 0xFE, 0xBA, 0xBE, 0xDE][..])
        );
    }

    #[test]
    fn cdr_le_layout_class_id_only() {
        // class_id="A" (1 char + NUL = len=2). Expected stream:
        //   uint32 len=2 LE: 02 00 00 00
        //   bytes        :  41 00
        //   pad-to-4     :  00 00
        //   prop_count=0 :  00 00 00 00
        //   bin_count=0  :  00 00 00 00
        let dh = DataHolder::new("A");
        let bytes = dh.to_cdr_le();
        assert_eq!(
            bytes,
            vec![
                0x02, 0x00, 0x00, 0x00, b'A', 0x00, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0
            ]
        );
    }

    #[test]
    fn truncated_buffer_is_error() {
        let err = DataHolder::from_cdr_le(&[0x10, 0x00, 0x00]).unwrap_err();
        assert_eq!(err.kind, SecurityErrorKind::BadArgument);
    }

    #[test]
    fn property_count_cap_rejects_huge() {
        // Forge a stream with prop_count = 1_000_000.
        let mut bytes = Vec::new();
        encode_string(&mut bytes, "X", true);
        encode_u32(&mut bytes, 1_000_000, true); // prop count > cap
        let err = DataHolder::from_cdr_le(&bytes).unwrap_err();
        assert_eq!(err.kind, SecurityErrorKind::BadArgument);
    }

    #[test]
    fn missing_trailing_nul_rejected() {
        // Forge: class_id len=1 (no NUL).
        let bytes = vec![0x01, 0x00, 0x00, 0x00, b'A'];
        let err = DataHolder::from_cdr_le(&bytes).unwrap_err();
        assert_eq!(err.kind, SecurityErrorKind::BadArgument);
    }

    #[test]
    fn dos_cap_overall_payload() {
        let big = vec![0u8; MAX_TOKEN_BYTES + 1];
        let err = DataHolder::from_cdr_le(&big).unwrap_err();
        assert_eq!(err.kind, SecurityErrorKind::BadArgument);
    }
}