Skip to main content

dvb_si/tables/
protection_message.rs

1//! Protection message sections — ETSI TS 102 809 v1.3.1 §9 (table_id 0x7B).
2//!
3//! Protection messages are MPEG-2 private sections (ISO/IEC 13818-1) used by
4//! the application-signalling authentication scheme. They share one table_id
5//! (0x7B) and are discriminated by the 16-bit `table_id_extension`
6//! ([`ProtectionMessageBody`], §9.3.4 Table 41, PDF p. 66):
7//!
8//! - `0x0000..=0x00FF` — **authentication message** (§9.4.3 Table 42, PDF
9//!   pp. 70-71). The extension *is* the `authentication_group_id`. Carries a
10//!   loop of section hashes plus a detached signature.
11//! - `0x0100` — **certificate collection message** (§9.5.4.9 Table 51, PDF
12//!   p. 91). The extension is the fixed `trust_message_id` 0x0100. Carries a
13//!   count-prefixed list of DER-encoded DVBCertificates.
14//! - `0x0101..=0xFFFF` — reserved for future use; preserved as a raw body so
15//!   parse → serialize stays byte-exact ([`ProtectionMessageBody::Raw`]).
16//!
17//! Mirrors the SAT precedent (`sat.rs`): a typed common section header plus a
18//! discriminated typed body. Variable-length inner loops (hash entries,
19//! certificate slices) are exposed as borrowed slices.
20//!
21//! Per crate contract this parser does NOT verify CRC_32 (use
22//! `Section::validate_crc`). Reserved bits are ignored on parse and emitted as
23//! 1s on serialize, except spec-mandated zero fields which are emitted 0.
24
25use crate::error::{Error, Result};
26use dvb_common::{Parse, Serialize};
27
28/// table_id for all protection messages (TS 102 809 §9.3.4; coded per EN 300 468 §5.1.3).
29pub const TABLE_ID: u8 = 0x7B;
30/// Protection messages have no well-known PID — they are carried on the PID(s)
31/// of the protectable elementary stream, signalled via the protection message
32/// descriptor (§9.3.3). Mirrors the `dsmcc.rs` "no fixed PID" convention.
33pub const PID: u16 = 0x0000;
34
35/// `table_id_extension` value (inclusive) of the first authentication message (§9.3.4 Table 41).
36pub const AUTH_EXTENSION_FIRST: u16 = 0x0000;
37/// `table_id_extension` value (inclusive) of the last authentication message (§9.3.4 Table 41).
38pub const AUTH_EXTENSION_LAST: u16 = 0x00FF;
39/// `table_id_extension` (`trust_message_id`) of the certificate collection message (§9.3.4 Table 41).
40pub const CERTIFICATE_COLLECTION_EXTENSION: u16 = 0x0100;
41
42/// Reference type coding — ETSI TS 102 809 §9.4.3 Table 45.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize))]
45#[non_exhaustive]
46pub enum ReferenceType {
47    /// 0x0 — reserved for future use.
48    Reserved,
49    /// 0x1 — same ES (table_id of the payload section).
50    SameEs,
51    /// 0x2 — component tag ES (component_tag of the payload section).
52    ComponentTagEs,
53    /// 0x3..=0xF — reserved.
54    Unallocated(u8),
55}
56
57impl ReferenceType {
58    #[must_use]
59    /// Decode from the wire value.  Every value maps (lossless).
60    pub fn from_u8(v: u8) -> Self {
61        match v & 0x0F {
62            0x0 => Self::Reserved,
63            0x1 => Self::SameEs,
64            0x2 => Self::ComponentTagEs,
65            v => Self::Unallocated(v),
66        }
67    }
68
69    #[must_use]
70    /// Encode to the wire value.  Inverse of `from_u8` / `from_u16`.
71    pub fn to_u8(self) -> u8 {
72        match self {
73            Self::Reserved => 0x0,
74            Self::SameEs => 0x1,
75            Self::ComponentTagEs => 0x2,
76            Self::Unallocated(v) => v,
77        }
78    }
79
80    #[must_use]
81    /// Human-readable spec display name.
82    pub fn name(self) -> &'static str {
83        match self {
84            Self::Reserved => "Reserved",
85            Self::SameEs => "Same ES",
86            Self::ComponentTagEs => "Component Tag ES",
87            Self::Unallocated(_) => "Unallocated",
88        }
89    }
90}
91
92/// table_id(1) + section_length hi/lo(2) + extension(2) + version/cni(1)
93/// + section_number(1) + last_section_number(1) = 8-byte common header.
94const HEADER_LEN: usize = 8;
95/// `section_length` counts from just after the field (byte 3) to end of section.
96const SECTION_LENGTH_PREFIX: usize = 3;
97/// CRC_32 trailer.
98const CRC_LEN: usize = 4;
99
100/// Authentication-message fixed body bytes after the common header, before the
101/// hash loop: section_hash_algorithm_identifier(1) + section_hash_length(1)
102/// + signature_algorithm_identifier(1) + reserved(4)|section_hashes_loop_length(12)(2).
103const AUTH_FIXED_PREFIX: usize = 5;
104
105/// One entry in the authentication message section-hash loop (§9.4.3 Table 42).
106///
107/// Each entry pairs a reference (locating the payload section the hash covers)
108/// with the truncated hash itself. `reference` length is the 4-bit
109/// `reference_length`; `hash` length is the section-wide `section_hash_length`.
110#[derive(Debug, Clone, PartialEq, Eq)]
111#[cfg_attr(feature = "serde", derive(serde::Serialize))]
112#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
113pub struct SectionHashEntry<'a> {
114    /// 4-bit `reference_type` (§9.4.3 Table 45): 1 = same ES, 2 = component_tag ES.
115    pub reference_type: ReferenceType,
116    /// `reference_byte` field — its semantics depend on `reference_type`.
117    pub reference: &'a [u8],
118    /// The (possibly truncated) section hash, `section_hash_length` bytes.
119    pub hash: &'a [u8],
120}
121
122/// Discriminated protection-message body, selected by `table_id_extension`.
123#[derive(Debug, Clone, PartialEq, Eq)]
124#[cfg_attr(feature = "serde", derive(serde::Serialize))]
125#[non_exhaustive]
126pub enum ProtectionMessageBody<'a> {
127    /// Authentication message (extension `0x0000..=0x00FF`; §9.4.3 Table 42).
128    AuthenticationMessage {
129        /// `section_hash_algorithm_identifier` (§9.4.3 Table 43): 0 = SHA-256, 1 = SHA-512.
130        section_hash_algorithm_identifier: u8,
131        /// `section_hash_length` — bytes per hash in each loop entry.
132        section_hash_length: u8,
133        /// `signature_algorithm_identifier` (§9.4.3 Table 44).
134        signature_algorithm_identifier: u8,
135        /// Section-hash loop entries in wire order.
136        hashes: Vec<SectionHashEntry<'a>>,
137        /// `extension_byte` payload (length-prefixed by `extension_bytes_length`).
138        extension_bytes: &'a [u8],
139        /// `signature_key_identifier_byte` payload (length-prefixed).
140        signature_key_identifier: &'a [u8],
141        /// Detached signature — runs from after the key identifier to the CRC.
142        signature: &'a [u8],
143    },
144    /// Certificate collection message (extension `0x0100`; §9.5.4.9 Table 51).
145    CertificateCollection {
146        /// DER-encoded DVBCertificate byte runs, one slice per `certificate_length` loop entry.
147        certificates: Vec<&'a [u8]>,
148    },
149    /// Reserved extension (`0x0101..=0xFFFF`) — body preserved verbatim.
150    Raw(&'a [u8]),
151}
152
153/// Protection message section (TS 102 809 §9; Tables 42 / 51).
154///
155/// Typed fields cover the common section header; [`ProtectionMessageSection::body`]
156/// carries the typed, discriminated body.
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[cfg_attr(feature = "serde", derive(serde::Serialize))]
159#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
160pub struct ProtectionMessageSection<'a> {
161    /// `table_id_extension` — `authentication_group_id` for authentication
162    /// messages, `trust_message_id` (0x0100) for certificate collections.
163    pub table_id_extension: u16,
164    /// 5-bit version_number.
165    pub version_number: u8,
166    /// current_next_indicator bit (spec mandates 1).
167    pub current_next_indicator: bool,
168    /// section_number.
169    pub section_number: u8,
170    /// last_section_number.
171    pub last_section_number: u8,
172    /// Discriminated body, selected by `table_id_extension`.
173    pub body: ProtectionMessageBody<'a>,
174}
175
176impl<'a> Parse<'a> for ProtectionMessageSection<'a> {
177    type Error = crate::error::Error;
178    fn parse(bytes: &'a [u8]) -> Result<Self> {
179        let min_len = HEADER_LEN + CRC_LEN;
180        if bytes.len() < min_len {
181            return Err(Error::BufferTooShort {
182                need: min_len,
183                have: bytes.len(),
184                what: "ProtectionMessageSection",
185            });
186        }
187        if bytes[0] != TABLE_ID {
188            return Err(Error::UnexpectedTableId {
189                table_id: bytes[0],
190                what: "ProtectionMessageSection",
191                expected: &[TABLE_ID],
192            });
193        }
194        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
195        let total = super::check_section_length(
196            bytes.len(),
197            SECTION_LENGTH_PREFIX,
198            section_length,
199            HEADER_LEN + CRC_LEN,
200        )?;
201
202        let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
203        let version_number = (bytes[5] >> 1) & 0x1F;
204        let current_next_indicator = bytes[5] & 0x01 != 0;
205        let section_number = bytes[6];
206        let last_section_number = bytes[7];
207
208        let body_bytes = &bytes[HEADER_LEN..total - CRC_LEN];
209        let body = match table_id_extension {
210            AUTH_EXTENSION_FIRST..=AUTH_EXTENSION_LAST => parse_authentication_message(body_bytes)?,
211            CERTIFICATE_COLLECTION_EXTENSION => parse_certificate_collection(body_bytes)?,
212            _ => ProtectionMessageBody::Raw(body_bytes),
213        };
214
215        Ok(ProtectionMessageSection {
216            table_id_extension,
217            version_number,
218            current_next_indicator,
219            section_number,
220            last_section_number,
221            body,
222        })
223    }
224}
225
226/// Parse the authentication-message body (§9.4.3 Table 42, PDF pp. 70-71).
227fn parse_authentication_message(body: &[u8]) -> Result<ProtectionMessageBody<'_>> {
228    if body.len() < AUTH_FIXED_PREFIX {
229        return Err(Error::BufferTooShort {
230            need: AUTH_FIXED_PREFIX,
231            have: body.len(),
232            what: "ProtectionMessageSection::AuthenticationMessage",
233        });
234    }
235    let section_hash_algorithm_identifier = body[0];
236    let section_hash_length = body[1];
237    let signature_algorithm_identifier = body[2];
238    // bytes[3] high nibble = reserved; section_hashes_loop_length is 12 bits.
239    let section_hashes_loop_length = (((body[3] & 0x0F) as usize) << 8) | body[4] as usize;
240
241    let loop_start = AUTH_FIXED_PREFIX;
242    let loop_end = loop_start + section_hashes_loop_length;
243    if loop_end > body.len() {
244        return Err(Error::SectionLengthOverflow {
245            declared: section_hashes_loop_length,
246            available: body.len() - loop_start,
247        });
248    }
249
250    let hash_len = section_hash_length as usize;
251    let mut hashes = Vec::new();
252    let mut pos = loop_start;
253    while pos < loop_end {
254        // reference_type(4) | reference_length(4)
255        let lead = body[pos];
256        let reference_type = ReferenceType::from_u8(lead >> 4);
257        let reference_length = (lead & 0x0F) as usize;
258        let ref_start = pos + 1;
259        let ref_end = ref_start + reference_length;
260        let hash_end = ref_end + hash_len;
261        if hash_end > loop_end {
262            return Err(Error::SectionLengthOverflow {
263                declared: reference_length + hash_len,
264                available: loop_end - ref_start,
265            });
266        }
267        hashes.push(SectionHashEntry {
268            reference_type,
269            reference: &body[ref_start..ref_end],
270            hash: &body[ref_end..hash_end],
271        });
272        pos = hash_end;
273    }
274
275    // extension_bytes_length(8) + extension bytes (§9.4.3 Table 42 tail).
276    if loop_end >= body.len() {
277        return Err(Error::BufferTooShort {
278            need: loop_end + 1,
279            have: body.len(),
280            what: "ProtectionMessageSection::extension_bytes_length",
281        });
282    }
283    let extension_bytes_length = body[loop_end] as usize;
284    let ext_start = loop_end + 1;
285    let ext_end = ext_start + extension_bytes_length;
286    if ext_end > body.len() {
287        return Err(Error::SectionLengthOverflow {
288            declared: extension_bytes_length,
289            available: body.len() - ext_start,
290        });
291    }
292
293    // signature_key_identifier_length(8) + key id bytes (Table 43 spillover, PDF p. 71).
294    if ext_end >= body.len() {
295        return Err(Error::BufferTooShort {
296            need: ext_end + 1,
297            have: body.len(),
298            what: "ProtectionMessageSection::signature_key_identifier_length",
299        });
300    }
301    let key_id_length = body[ext_end] as usize;
302    let key_start = ext_end + 1;
303    let key_end = key_start + key_id_length;
304    if key_end > body.len() {
305        return Err(Error::SectionLengthOverflow {
306            declared: key_id_length,
307            available: body.len() - key_start,
308        });
309    }
310
311    // signature_byte loop runs to the end of the body (i.e. up to the CRC_32).
312    let signature = &body[key_end..];
313
314    Ok(ProtectionMessageBody::AuthenticationMessage {
315        section_hash_algorithm_identifier,
316        section_hash_length,
317        signature_algorithm_identifier,
318        hashes,
319        extension_bytes: &body[ext_start..ext_end],
320        signature_key_identifier: &body[key_start..key_end],
321        signature,
322    })
323}
324
325/// Parse the certificate-collection body (§9.5.4.9 Table 51, PDF p. 91).
326fn parse_certificate_collection(body: &[u8]) -> Result<ProtectionMessageBody<'_>> {
327    if body.is_empty() {
328        return Err(Error::BufferTooShort {
329            need: 1,
330            have: 0,
331            what: "ProtectionMessageSection::CertificateCollection",
332        });
333    }
334    // byte 0: reserved(4) | certificate_count(4)
335    let certificate_count = (body[0] & 0x0F) as usize;
336    let mut certificates = Vec::with_capacity(certificate_count);
337    let mut pos = 1;
338    for _ in 0..certificate_count {
339        if pos + 2 > body.len() {
340            return Err(Error::BufferTooShort {
341                need: pos + 2,
342                have: body.len(),
343                what: "ProtectionMessageSection::certificate_length",
344            });
345        }
346        // reserved(4) | certificate_length(12)
347        let certificate_length = (((body[pos] & 0x0F) as usize) << 8) | body[pos + 1] as usize;
348        let cert_start = pos + 2;
349        let cert_end = cert_start + certificate_length;
350        if cert_end > body.len() {
351            return Err(Error::SectionLengthOverflow {
352                declared: certificate_length,
353                available: body.len() - cert_start,
354            });
355        }
356        certificates.push(&body[cert_start..cert_end]);
357        pos = cert_end;
358    }
359    Ok(ProtectionMessageBody::CertificateCollection { certificates })
360}
361
362impl ProtectionMessageBody<'_> {
363    /// Serialized length of the body (excluding common header and CRC).
364    fn body_len(&self) -> usize {
365        match self {
366            ProtectionMessageBody::AuthenticationMessage {
367                hashes,
368                extension_bytes,
369                signature_key_identifier,
370                signature,
371                ..
372            } => {
373                let loop_bytes: usize = hashes
374                    .iter()
375                    .map(|h| 1 + h.reference.len() + h.hash.len())
376                    .sum();
377                AUTH_FIXED_PREFIX
378                    + loop_bytes
379                    + 1
380                    + extension_bytes.len()
381                    + 1
382                    + signature_key_identifier.len()
383                    + signature.len()
384            }
385            ProtectionMessageBody::CertificateCollection { certificates } => {
386                1 + certificates.iter().map(|c| 2 + c.len()).sum::<usize>()
387            }
388            ProtectionMessageBody::Raw(raw) => raw.len(),
389        }
390    }
391
392    /// Write the body into `buf`, returning the number of bytes written.
393    fn write_into(&self, buf: &mut [u8]) -> Result<usize> {
394        match self {
395            ProtectionMessageBody::AuthenticationMessage {
396                section_hash_algorithm_identifier,
397                section_hash_length,
398                signature_algorithm_identifier,
399                hashes,
400                extension_bytes,
401                signature_key_identifier,
402                signature,
403            } => {
404                buf[0] = *section_hash_algorithm_identifier;
405                buf[1] = *section_hash_length;
406                buf[2] = *signature_algorithm_identifier;
407                let loop_bytes: usize = hashes
408                    .iter()
409                    .map(|h| 1 + h.reference.len() + h.hash.len())
410                    .sum();
411                if loop_bytes > 0x0FFF {
412                    return Err(Error::SectionLengthOverflow {
413                        declared: loop_bytes,
414                        available: 0x0FFF,
415                    });
416                }
417                if extension_bytes.len() > u8::MAX as usize {
418                    return Err(Error::SectionLengthOverflow {
419                        declared: extension_bytes.len(),
420                        available: u8::MAX as usize,
421                    });
422                }
423                if signature_key_identifier.len() > u8::MAX as usize {
424                    return Err(Error::SectionLengthOverflow {
425                        declared: signature_key_identifier.len(),
426                        available: u8::MAX as usize,
427                    });
428                }
429                // reserved(4) emitted 1s | section_hashes_loop_length(12).
430                buf[3] = 0xF0 | ((loop_bytes >> 8) as u8 & 0x0F);
431                buf[4] = (loop_bytes & 0xFF) as u8;
432                let mut pos = AUTH_FIXED_PREFIX;
433                for h in hashes {
434                    if h.reference.len() > 0x0F {
435                        return Err(Error::SectionLengthOverflow {
436                            declared: h.reference.len(),
437                            available: 0x0F,
438                        });
439                    }
440                    buf[pos] = (h.reference_type.to_u8() << 4) | (h.reference.len() as u8 & 0x0F);
441                    pos += 1;
442                    buf[pos..pos + h.reference.len()].copy_from_slice(h.reference);
443                    pos += h.reference.len();
444                    buf[pos..pos + h.hash.len()].copy_from_slice(h.hash);
445                    pos += h.hash.len();
446                }
447                buf[pos] = extension_bytes.len() as u8;
448                pos += 1;
449                buf[pos..pos + extension_bytes.len()].copy_from_slice(extension_bytes);
450                pos += extension_bytes.len();
451                buf[pos] = signature_key_identifier.len() as u8;
452                pos += 1;
453                buf[pos..pos + signature_key_identifier.len()]
454                    .copy_from_slice(signature_key_identifier);
455                pos += signature_key_identifier.len();
456                buf[pos..pos + signature.len()].copy_from_slice(signature);
457                pos += signature.len();
458                Ok(pos)
459            }
460            ProtectionMessageBody::CertificateCollection { certificates } => {
461                if certificates.len() > 0x0F {
462                    return Err(Error::SectionLengthOverflow {
463                        declared: certificates.len(),
464                        available: 0x0F,
465                    });
466                }
467                // reserved(4) emitted 1s | certificate_count(4).
468                buf[0] = 0xF0 | (certificates.len() as u8 & 0x0F);
469                let mut pos = 1;
470                for c in certificates {
471                    if c.len() > 0x0FFF {
472                        return Err(Error::SectionLengthOverflow {
473                            declared: c.len(),
474                            available: 0x0FFF,
475                        });
476                    }
477                    // reserved(4) emitted 1s | certificate_length(12).
478                    buf[pos] = 0xF0 | ((c.len() >> 8) as u8 & 0x0F);
479                    buf[pos + 1] = (c.len() & 0xFF) as u8;
480                    pos += 2;
481                    buf[pos..pos + c.len()].copy_from_slice(c);
482                    pos += c.len();
483                }
484                Ok(pos)
485            }
486            ProtectionMessageBody::Raw(raw) => {
487                buf[..raw.len()].copy_from_slice(raw);
488                Ok(raw.len())
489            }
490        }
491    }
492}
493
494impl Serialize for ProtectionMessageSection<'_> {
495    type Error = crate::error::Error;
496    fn serialized_len(&self) -> usize {
497        HEADER_LEN + self.body.body_len() + CRC_LEN
498    }
499    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
500        let len = self.serialized_len();
501        if buf.len() < len {
502            return Err(Error::OutputBufferTooSmall {
503                need: len,
504                have: buf.len(),
505            });
506        }
507        let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
508        buf[0] = TABLE_ID;
509        buf[1] = super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F);
510        buf[2] = (section_length & 0xFF) as u8;
511        buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
512        // reserved(2)=11, version_number(5), current_next_indicator(1).
513        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
514        buf[6] = self.section_number;
515        buf[7] = self.last_section_number;
516        let body_written = self.body.write_into(&mut buf[HEADER_LEN..])?;
517        let body_end = HEADER_LEN + body_written;
518        let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
519        buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
520        Ok(len)
521    }
522}
523impl<'a> crate::traits::TableDef<'a> for ProtectionMessageSection<'a> {
524    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
525    const NAME: &'static str = "PROTECTION_MESSAGE";
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    /// Wrap a body in the 8-byte common header + placeholder CRC.
533    fn build_section(extension: u16, version: u8, body: &[u8]) -> Vec<u8> {
534        let section_length = (HEADER_LEN - SECTION_LENGTH_PREFIX + body.len() + CRC_LEN) as u16;
535        let mut v = vec![
536            TABLE_ID,
537            super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F),
538            (section_length & 0xFF) as u8,
539            (extension >> 8) as u8,
540            (extension & 0xFF) as u8,
541            0xC0 | (version << 1) | 0x01,
542            0x00,
543            0x00,
544        ];
545        v.extend_from_slice(body);
546        v.extend_from_slice(&[0, 0, 0, 0]);
547        v
548    }
549
550    /// Build an authentication-message body: one hash entry + ext + key id + signature.
551    fn auth_body() -> Vec<u8> {
552        let reference = [0x01]; // reference_type 1 => table_id of payload section
553        let hash = [0xAA, 0xBB, 0xCC, 0xDD]; // section_hash_length = 4
554        let mut hashes_loop = vec![(1u8 << 4) | (reference.len() as u8)]; // reference_type 1, length 1
555        hashes_loop.extend_from_slice(&reference);
556        hashes_loop.extend_from_slice(&hash);
557        let loop_len = hashes_loop.len();
558
559        let mut b = vec![
560            0x00,                                  // section_hash_algorithm_identifier = SHA-256
561            hash.len() as u8,                      // section_hash_length = 4
562            0x01,                                  // signature_algorithm_identifier = ed25519
563            0xF0 | ((loop_len >> 8) as u8 & 0x0F), // reserved | loop_length hi
564            (loop_len & 0xFF) as u8,               // loop_length lo
565        ];
566        b.extend_from_slice(&hashes_loop);
567        // extension_bytes_length + bytes
568        b.push(2);
569        b.extend_from_slice(&[0xDE, 0xAD]);
570        // signature_key_identifier_length + bytes
571        b.push(3);
572        b.extend_from_slice(&[0x11, 0x22, 0x33]);
573        // signature (runs to CRC)
574        b.extend_from_slice(&[0x90, 0x91, 0x92, 0x93, 0x94, 0x95]);
575        b
576    }
577
578    /// Build a certificate-collection body with two certificate slices.
579    fn cert_body() -> Vec<u8> {
580        let c0: &[u8] = &[0x30, 0x82, 0x01, 0x02];
581        let c1: &[u8] = &[0xAB, 0xCD];
582        let mut b = vec![0xF0 | 0x02]; // reserved | certificate_count = 2
583        b.push(0xF0 | ((c0.len() >> 8) as u8 & 0x0F));
584        b.push((c0.len() & 0xFF) as u8);
585        b.extend_from_slice(c0);
586        b.push(0xF0 | ((c1.len() >> 8) as u8 & 0x0F));
587        b.push((c1.len() & 0xFF) as u8);
588        b.extend_from_slice(c1);
589        b
590    }
591
592    #[test]
593    fn parse_authentication_message() {
594        let bytes = build_section(0x0042, 5, &auth_body());
595        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
596        assert_eq!(sec.table_id_extension, 0x0042);
597        assert_eq!(sec.version_number, 5);
598        assert!(sec.current_next_indicator);
599        match sec.body {
600            ProtectionMessageBody::AuthenticationMessage {
601                section_hash_algorithm_identifier,
602                section_hash_length,
603                signature_algorithm_identifier,
604                hashes,
605                extension_bytes,
606                signature_key_identifier,
607                signature,
608            } => {
609                assert_eq!(section_hash_algorithm_identifier, 0x00);
610                assert_eq!(section_hash_length, 4);
611                assert_eq!(signature_algorithm_identifier, 0x01);
612                assert_eq!(hashes.len(), 1);
613                assert_eq!(hashes[0].reference_type, ReferenceType::SameEs);
614                assert_eq!(hashes[0].reference, &[0x01]);
615                assert_eq!(hashes[0].hash, &[0xAA, 0xBB, 0xCC, 0xDD]);
616                assert_eq!(extension_bytes, &[0xDE, 0xAD]);
617                assert_eq!(signature_key_identifier, &[0x11, 0x22, 0x33]);
618                assert_eq!(signature, &[0x90, 0x91, 0x92, 0x93, 0x94, 0x95]);
619            }
620            other => panic!("expected AuthenticationMessage, got {other:?}"),
621        }
622    }
623
624    #[test]
625    fn parse_certificate_collection() {
626        let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 0, &cert_body());
627        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
628        assert_eq!(sec.table_id_extension, 0x0100);
629        match sec.body {
630            ProtectionMessageBody::CertificateCollection { certificates } => {
631                assert_eq!(certificates.len(), 2);
632                assert_eq!(certificates[0], &[0x30, 0x82, 0x01, 0x02]);
633                assert_eq!(certificates[1], &[0xAB, 0xCD]);
634            }
635            other => panic!("expected CertificateCollection, got {other:?}"),
636        }
637    }
638
639    #[test]
640    fn reserved_extension_kept_raw() {
641        let raw = [0x01, 0x02, 0x03, 0x04];
642        let bytes = build_section(0x0200, 0, &raw);
643        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
644        assert!(matches!(sec.body, ProtectionMessageBody::Raw(b) if b == raw));
645    }
646
647    #[test]
648    fn parse_rejects_wrong_tag() {
649        let mut bytes = build_section(0x0000, 0, &auth_body());
650        bytes[0] = 0x4D;
651        assert!(matches!(
652            ProtectionMessageSection::parse(&bytes).unwrap_err(),
653            Error::UnexpectedTableId { table_id: 0x4D, .. }
654        ));
655    }
656
657    #[test]
658    fn rejects_short_buffer() {
659        assert!(matches!(
660            ProtectionMessageSection::parse(&[0x7B, 0xB0]).unwrap_err(),
661            Error::BufferTooShort {
662                what: "ProtectionMessageSection",
663                ..
664            }
665        ));
666    }
667
668    #[test]
669    fn auth_loop_overflow_rejected() {
670        let mut body = vec![0x00, 0x04, 0x01, 0xF0, 0xFF];
671        body.extend_from_slice(&[0x00]);
672        let bytes = build_section(0x0000, 0, &body);
673        assert!(matches!(
674            ProtectionMessageSection::parse(&bytes).unwrap_err(),
675            Error::SectionLengthOverflow { .. }
676        ));
677    }
678
679    #[test]
680    fn cert_length_overflow_rejected() {
681        let body = vec![0xF0 | 0x01, 0x00, 0x10, 0x01];
682        let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 0, &body);
683        assert!(matches!(
684            ProtectionMessageSection::parse(&bytes).unwrap_err(),
685            Error::SectionLengthOverflow { .. }
686        ));
687    }
688
689    #[test]
690    fn round_trip_authentication_message() {
691        let bytes = build_section(0x0042, 7, &auth_body());
692        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
693        let mut buf = vec![0u8; sec.serialized_len()];
694        sec.serialize_into(&mut buf).unwrap();
695        let re = ProtectionMessageSection::parse(&buf).unwrap();
696        assert_eq!(sec, re);
697    }
698
699    #[test]
700    fn round_trip_certificate_collection() {
701        let bytes = build_section(CERTIFICATE_COLLECTION_EXTENSION, 3, &cert_body());
702        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
703        let mut buf = vec![0u8; sec.serialized_len()];
704        sec.serialize_into(&mut buf).unwrap();
705        let re = ProtectionMessageSection::parse(&buf).unwrap();
706        assert_eq!(sec, re);
707    }
708
709    #[test]
710    fn round_trip_raw_reserved() {
711        let bytes = build_section(0xABCD, 1, &[0xDE, 0xAD, 0xBE, 0xEF]);
712        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
713        let mut buf = vec![0u8; sec.serialized_len()];
714        sec.serialize_into(&mut buf).unwrap();
715        let re = ProtectionMessageSection::parse(&buf).unwrap();
716        assert_eq!(sec, re);
717    }
718
719    #[test]
720    fn table_trait_constants() {
721        assert_eq!(TABLE_ID, 0x7B);
722        assert_eq!(PID, 0x0000);
723    }
724
725    #[test]
726    #[cfg(feature = "serde")]
727    fn serde_json_round_trip() {
728        let bytes = build_section(0x0042, 5, &auth_body());
729        let sec = ProtectionMessageSection::parse(&bytes).unwrap();
730        let j = serde_json::to_string(&sec).unwrap();
731        let reparsed = ProtectionMessageSection::parse(&bytes).unwrap();
732        assert_eq!(serde_json::to_string(&reparsed).unwrap(), j);
733        assert!(j.contains("\"signature_algorithm_identifier\":1"));
734    }
735
736    #[test]
737    fn parse_rejects_zero_section_length() {
738        let mut buf = vec![0u8; 64];
739        buf[0] = TABLE_ID;
740        buf[1] = 0xF0;
741        buf[2] = 0x00;
742        for b in &mut buf[3..] {
743            *b = 0xFF;
744        }
745        assert!(matches!(
746            ProtectionMessageSection::parse(&buf).unwrap_err(),
747            Error::SectionLengthOverflow { .. }
748        ));
749    }
750
751    #[test]
752    fn reference_type_full_range_round_trip() {
753        for v in 0u8..=0x0F {
754            let rt = ReferenceType::from_u8(v);
755            assert_eq!(
756                rt.to_u8(),
757                v,
758                "ReferenceType round-trip failed for {v:#04x}"
759            );
760        }
761    }
762}