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