Skip to main content

bgpkit_parser/parser/bgp/attributes/
mod.rs

1mod attr_01_origin;
2mod attr_02_17_as_path;
3pub(crate) mod attr_03_next_hop;
4mod attr_04_med;
5mod attr_05_local_pref;
6mod attr_07_18_aggregator;
7mod attr_08_communities;
8mod attr_09_originator;
9mod attr_10_13_cluster;
10mod attr_14_15_nlri;
11mod attr_16_25_extended_communities;
12mod attr_23_tunnel_encap;
13mod attr_24_traffic_engineering;
14mod attr_26_aigp;
15mod attr_29_linkstate;
16mod attr_32_large_communities;
17mod attr_35_otc;
18mod attr_36_domain_path;
19mod attr_37_sfp;
20mod attr_38_bfd_discriminator;
21mod attr_40_bgp_prefix_sid;
22mod attr_41_bier;
23
24use bytes::{Buf, BufMut, Bytes, BytesMut};
25use log::{debug, warn};
26use std::net::IpAddr;
27
28use crate::models::*;
29
30use crate::encoder::sink::{with_u16_len, with_u8_len};
31use crate::error::{BgpValidationWarning, EncodingError, ParserError};
32use crate::parser::bgp::attributes::attr_01_origin::{encode_origin, parse_origin};
33use crate::parser::bgp::attributes::attr_02_17_as_path::encode_as_path;
34pub(crate) use crate::parser::bgp::attributes::attr_02_17_as_path::validate_as_path_slice;
35pub(crate) use crate::parser::bgp::attributes::attr_02_17_as_path::{
36    parse_as_path, parse_as_path_slice,
37};
38use crate::parser::bgp::attributes::attr_03_next_hop::{encode_next_hop, parse_next_hop};
39use crate::parser::bgp::attributes::attr_04_med::{encode_med, parse_med};
40use crate::parser::bgp::attributes::attr_05_local_pref::{encode_local_pref, parse_local_pref};
41pub(crate) use crate::parser::bgp::attributes::attr_07_18_aggregator::parse_aggregator as parse_aggregator_slice;
42use crate::parser::bgp::attributes::attr_07_18_aggregator::{encode_aggregator, parse_aggregator};
43pub(crate) use crate::parser::bgp::attributes::attr_08_communities::{
44    decode_regular_community, parse_regular_communities as parse_communities_attribute,
45};
46use crate::parser::bgp::attributes::attr_08_communities::{
47    encode_regular_communities, parse_regular_communities,
48};
49use crate::parser::bgp::attributes::attr_09_originator::{
50    encode_originator_id, parse_originator_id,
51};
52use crate::parser::bgp::attributes::attr_10_13_cluster::{encode_clusters, parse_clusters};
53use crate::parser::bgp::attributes::attr_14_15_nlri::encode_nlri;
54pub(crate) use crate::parser::bgp::attributes::attr_14_15_nlri::parse_nlri;
55use crate::parser::bgp::attributes::attr_16_25_extended_communities::{
56    encode_extended_communities, encode_ipv6_extended_communities, parse_extended_community,
57    parse_ipv6_extended_community,
58};
59pub(crate) use crate::parser::bgp::attributes::attr_16_25_extended_communities::{
60    parse_extended_community as parse_extended_communities_attribute, parse_extended_community_one,
61    parse_ipv6_extended_community as parse_ipv6_extended_communities_attribute,
62    parse_ipv6_extended_community_one,
63};
64use crate::parser::bgp::attributes::attr_23_tunnel_encap::{
65    encode_tunnel_encapsulation_attribute, parse_tunnel_encapsulation_attribute,
66};
67use crate::parser::bgp::attributes::attr_24_traffic_engineering::encode_traffic_engineering;
68pub(crate) use crate::parser::bgp::attributes::attr_24_traffic_engineering::parse_traffic_engineering;
69use crate::parser::bgp::attributes::attr_26_aigp::{encode_aigp, parse_aigp};
70use crate::parser::bgp::attributes::attr_29_linkstate::{
71    encode_link_state_attribute, parse_link_state_attribute,
72};
73pub(crate) use crate::parser::bgp::attributes::attr_32_large_communities::parse_large_communities as parse_large_communities_attribute;
74use crate::parser::bgp::attributes::attr_32_large_communities::{
75    encode_large_communities, parse_large_communities,
76};
77use crate::parser::bgp::attributes::attr_35_otc::{
78    encode_only_to_customer, parse_only_to_customer,
79};
80use crate::parser::bgp::attributes::attr_36_domain_path::{encode_domain_path, parse_domain_path};
81use crate::parser::bgp::attributes::attr_37_sfp::{encode_sfp, parse_sfp};
82use crate::parser::bgp::attributes::attr_38_bfd_discriminator::{
83    encode_bfd_discriminator, parse_bfd_discriminator,
84};
85use crate::parser::bgp::attributes::attr_40_bgp_prefix_sid::{
86    encode_bgp_prefix_sid, parse_bgp_prefix_sid,
87};
88use crate::parser::bgp::attributes::attr_41_bier::{encode_bier, parse_bier};
89use crate::parser::ReadUtils;
90
91/// Validate attribute flags according to RFC 4271 and RFC 7606
92fn validate_attribute_flags(
93    attr_type: AttrType,
94    flags: AttrFlags,
95    warnings: &mut Vec<BgpValidationWarning>,
96) {
97    let expected_flags = match attr_type {
98        // Well-known mandatory attributes
99        AttrType::ORIGIN | AttrType::AS_PATH | AttrType::NEXT_HOP => AttrFlags::TRANSITIVE,
100        // Well-known discretionary attributes
101        AttrType::ATOMIC_AGGREGATE => AttrFlags::TRANSITIVE,
102        // Optional non-transitive attributes
103        AttrType::MULTI_EXIT_DISCRIMINATOR
104        | AttrType::ORIGINATOR_ID
105        | AttrType::CLUSTER_LIST
106        | AttrType::MP_REACHABLE_NLRI
107        | AttrType::MP_UNREACHABLE_NLRI
108        | AttrType::TRAFFIC_ENGINEERING => AttrFlags::OPTIONAL,
109        // Optional transitive attributes
110        AttrType::AGGREGATOR
111        | AttrType::AS4_AGGREGATOR
112        | AttrType::AS4_PATH
113        | AttrType::COMMUNITIES
114        | AttrType::EXTENDED_COMMUNITIES
115        | AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
116        | AttrType::LARGE_COMMUNITIES
117        | AttrType::ONLY_TO_CUSTOMER
118        | AttrType::BGP_DOMAIN_PATH => AttrFlags::OPTIONAL | AttrFlags::TRANSITIVE,
119        // LOCAL_PREFERENCE is well-known mandatory for IBGP
120        AttrType::LOCAL_PREFERENCE => AttrFlags::TRANSITIVE,
121        // Unknown or development attributes
122        _ => return, // Don't validate unknown attributes
123    };
124
125    // Check if flags match expected (ignoring EXTENDED and PARTIAL flags for this check)
126    let relevant_flags = flags & (AttrFlags::OPTIONAL | AttrFlags::TRANSITIVE);
127    if relevant_flags != expected_flags {
128        warnings.push(BgpValidationWarning::AttributeFlagsError {
129            attr_type,
130            expected_flags: expected_flags.bits(),
131            actual_flags: relevant_flags.bits(),
132        });
133    }
134
135    // Check partial flag constraint
136    if flags.contains(AttrFlags::PARTIAL) {
137        match attr_type {
138            // Partial bit MUST be 0 for well-known attributes and optional non-transitive
139            AttrType::ORIGIN
140            | AttrType::AS_PATH
141            | AttrType::NEXT_HOP
142            | AttrType::LOCAL_PREFERENCE
143            | AttrType::ATOMIC_AGGREGATE
144            | AttrType::MULTI_EXIT_DISCRIMINATOR
145            | AttrType::ORIGINATOR_ID
146            | AttrType::CLUSTER_LIST
147            | AttrType::MP_REACHABLE_NLRI
148            | AttrType::MP_UNREACHABLE_NLRI
149            | AttrType::TRAFFIC_ENGINEERING => {
150                warnings.push(BgpValidationWarning::AttributeFlagsError {
151                    attr_type,
152                    expected_flags: expected_flags.bits(),
153                    actual_flags: flags.bits(),
154                });
155            }
156            _ => {} // Partial is OK for optional transitive attributes
157        }
158    }
159}
160
161pub(crate) fn is_raw_retained_attr(attr_type: AttrType) -> bool {
162    matches!(
163        attr_type,
164        AttrType::RESERVED
165            | AttrType::PMSI_TUNNEL
166            | AttrType::PE_DISTINGUISHER_LABELS
167            | AttrType::BGPSEC_PATH
168            | AttrType::ATTR_SET
169    )
170}
171
172/// Check if an attribute type is well-known mandatory
173fn is_well_known_mandatory(attr_type: AttrType) -> bool {
174    matches!(
175        attr_type,
176        AttrType::ORIGIN | AttrType::AS_PATH | AttrType::NEXT_HOP | AttrType::LOCAL_PREFERENCE
177    )
178}
179
180pub(crate) struct AttributeValidationState {
181    warnings: Vec<BgpValidationWarning>,
182    attr_mask: [u64; 4],
183}
184
185impl AttributeValidationState {
186    pub(crate) fn new() -> Self {
187        Self {
188            warnings: Vec::new(),
189            attr_mask: [0; 4],
190        }
191    }
192
193    fn has_raw_attr(&self, attr: u8) -> bool {
194        (self.attr_mask[(attr / 64) as usize] & (1u64 << (attr % 64))) != 0
195    }
196
197    pub(crate) fn has_attr(&self, attr_type: AttrType) -> bool {
198        self.has_raw_attr(u8::from(attr_type))
199    }
200
201    fn set_attr(&mut self, attr: u8) {
202        self.attr_mask[(attr / 64) as usize] |= 1u64 << (attr % 64);
203    }
204
205    pub(crate) fn observe_header(
206        &mut self,
207        raw_attr_type: u8,
208        attr_type: AttrType,
209        flags: AttrFlags,
210        length: usize,
211    ) -> bool {
212        if self.has_raw_attr(raw_attr_type) {
213            self.warnings
214                .push(BgpValidationWarning::DuplicateAttribute { attr_type });
215        }
216        self.set_attr(raw_attr_type);
217
218        validate_attribute_flags(attr_type, flags, &mut self.warnings);
219        validate_attribute_length(attr_type, length, &mut self.warnings);
220
221        flags.contains(AttrFlags::PARTIAL)
222    }
223
224    pub(crate) fn observe_parse_error(
225        &mut self,
226        attr_type: AttrType,
227        partial: bool,
228        error: &ParserError,
229    ) {
230        if partial {
231            self.warnings
232                .push(BgpValidationWarning::PartialAttributeError {
233                    attr_type,
234                    reason: error.to_string(),
235                });
236            debug!("PARTIAL attribute error: {}", error);
237        } else if is_well_known_mandatory(attr_type) {
238            self.warnings
239                .push(BgpValidationWarning::MalformedAttributeList {
240                    reason: format!(
241                        "Well-known mandatory attribute {} parsing failed: {}",
242                        u8::from(attr_type),
243                        error
244                    ),
245                });
246            debug!(
247                "Well-known mandatory attribute parsing failed, treating as withdraw: {}",
248                error
249            );
250        } else {
251            self.warnings
252                .push(BgpValidationWarning::OptionalAttributeError {
253                    attr_type,
254                    reason: error.to_string(),
255                });
256            debug!("Optional attribute error, discarding: {}", error);
257        }
258    }
259
260    pub(crate) fn check_mandatory_attributes(
261        &mut self,
262        is_announcement: bool,
263        has_standard_nlri: bool,
264    ) {
265        if !is_announcement {
266            return;
267        }
268
269        if !self.has_attr(AttrType::ORIGIN) {
270            self.warnings
271                .push(BgpValidationWarning::MissingWellKnownAttribute {
272                    attr_type: AttrType::ORIGIN,
273                });
274        }
275
276        if !self.has_attr(AttrType::AS_PATH) {
277            self.warnings
278                .push(BgpValidationWarning::MissingWellKnownAttribute {
279                    attr_type: AttrType::AS_PATH,
280                });
281        }
282
283        let has_mp_reach = self.has_attr(AttrType::MP_REACHABLE_NLRI);
284        if (has_standard_nlri || !has_mp_reach) && !self.has_attr(AttrType::NEXT_HOP) {
285            self.warnings
286                .push(BgpValidationWarning::MissingWellKnownAttribute {
287                    attr_type: AttrType::NEXT_HOP,
288                });
289        }
290    }
291
292    pub(crate) fn finish(self) -> (Vec<BgpValidationWarning>, [u64; 4]) {
293        (self.warnings, self.attr_mask)
294    }
295}
296
297/// Validate attribute length constraints
298fn validate_attribute_length(
299    attr_type: AttrType,
300    length: usize,
301    warnings: &mut Vec<BgpValidationWarning>,
302) {
303    let expected_length = match attr_type {
304        AttrType::ORIGIN => Some(1),
305        AttrType::NEXT_HOP => Some(4), // IPv4 next hop
306        AttrType::MULTI_EXIT_DISCRIMINATOR => Some(4),
307        AttrType::LOCAL_PREFERENCE => Some(4),
308        AttrType::ATOMIC_AGGREGATE => Some(0),
309        AttrType::ORIGINATOR_ID => Some(4),
310        AttrType::ONLY_TO_CUSTOMER => Some(4),
311        // Variable length attributes - no fixed constraint
312        AttrType::AS_PATH
313        | AttrType::AS4_PATH
314        | AttrType::AGGREGATOR
315        | AttrType::AS4_AGGREGATOR
316        | AttrType::COMMUNITIES
317        | AttrType::EXTENDED_COMMUNITIES
318        | AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
319        | AttrType::LARGE_COMMUNITIES
320        | AttrType::CLUSTER_LIST
321        | AttrType::MP_REACHABLE_NLRI
322        | AttrType::MP_UNREACHABLE_NLRI => None,
323        _ => None, // Unknown attributes
324    };
325
326    if let Some(expected) = expected_length {
327        if length != expected {
328            warnings.push(BgpValidationWarning::AttributeLengthError {
329                attr_type,
330                expected_length: Some(expected),
331                actual_length: length,
332            });
333        }
334    }
335}
336
337/// Whether RFC 10039 §4 allows the D-PATH attribute on routes of this family: IPVPN, which is
338/// IPv4 or IPv6 with SAFI 128, and EVPN, which is AFI 25 with SAFI 70.
339fn is_domain_path_family(afi: u16, safi: u8) -> bool {
340    matches!((afi, safi), (1 | 2, 128) | (25, 70))
341}
342
343/// The AFI/SAFI header an MP_REACH_NLRI attribute value starts with, when it is long enough to
344/// carry one. The header identifies the family even when the rest did not decode.
345fn mp_reach_family(bytes: &[u8]) -> Option<(u16, u8)> {
346    match bytes.len() >= 3 {
347        true => Some((u16::from_be_bytes([bytes[0], bytes[1]]), bytes[2])),
348        false => None,
349    }
350}
351
352/// The route families a D-PATH-carrying message carries, as far as the caller can tell.
353#[derive(Debug, Clone, Copy, Default)]
354struct DomainPathFamilies {
355    /// Family the caller already knows, e.g. a RIB entry from its record header.
356    declared: Option<(u16, u8)>,
357    /// Family of the routes an MP_REACH_NLRI announces, decoded or read off its header.
358    announced: Option<(u16, u8)>,
359    /// Classic IPv4 unicast NLRI, which the UPDATE parser adds once it has parsed them.
360    classic_ipv4: bool,
361}
362
363impl DomainPathFamilies {
364    /// The families visible in an attribute set on its own, before any NLRI is parsed. An
365    /// MP_UNREACH_NLRI announces nothing, so it says nothing about the family here. An
366    /// MP_REACH_NLRI whose NLRI did not decode still identifies its family through the AFI/SAFI
367    /// header it starts with, which is enough to judge it.
368    fn from_attributes(attributes: &[Attribute], declared: Option<(u16, u8)>) -> Self {
369        let announced = attributes
370            .iter()
371            .find_map(|attribute| match &attribute.value {
372                AttributeValue::MpReachNlri(nlri) => Some((nlri.afi as u16, nlri.safi as u8)),
373                _ => None,
374            })
375            .or_else(|| {
376                attributes
377                    .iter()
378                    .find_map(|attribute| match &attribute.value {
379                        AttributeValue::Raw(raw) | AttributeValue::Unknown(raw)
380                            if raw.code == u8::from(AttrType::MP_REACHABLE_NLRI) =>
381                        {
382                            mp_reach_family(&raw.bytes)
383                        }
384                        _ => None,
385                    })
386            });
387
388        DomainPathFamilies {
389            declared,
390            announced,
391            classic_ipv4: false,
392        }
393    }
394
395    /// Describe a carried family that RFC 10039 §4 does not allow D-PATH on, if there is one.
396    ///
397    /// The rule is about the routes a message carries, so a decoded announcement decides the
398    /// answer and a withdrawal never introduces one. A family this attribute set does not
399    /// reveal stays unknown: the UPDATE parser reports classic IPv4 unicast NLRI once it has
400    /// parsed them, and a caller that knows the family up front passes it in.
401    fn disallowed(&self) -> Option<String> {
402        let declared = self
403            .declared
404            .filter(|(afi, safi)| !is_domain_path_family(*afi, *safi));
405        if let Some((afi, safi)) = declared {
406            return Some(describe_family(afi, safi, "declared"));
407        }
408
409        if let Some((afi, safi)) = self
410            .announced
411            .filter(|(afi, safi)| !is_domain_path_family(*afi, *safi))
412        {
413            return Some(describe_family(afi, safi, "announced"));
414        }
415
416        if self.classic_ipv4 {
417            return Some("classic IPv4 unicast NLRI (AFI 1, SAFI 1)".to_string());
418        }
419
420        None
421    }
422}
423
424fn describe_family(afi: u16, safi: u8, source: &str) -> String {
425    match (afi, safi) {
426        // a mismatched EVPN SAFI is worth naming, since EVPN is AFI 25 with SAFI 70
427        (_, 70) if afi != 25 => {
428            format!("{source} AFI {afi} routes with SAFI 70 (EVPN requires AFI 25)")
429        }
430        _ => format!("{source} AFI {afi} routes with SAFI {safi}"),
431    }
432}
433
434/// RFC 10039 §4 limits D-PATH to UPDATEs that carry IPVPN or EVPN routes and requires the
435/// treat-as-withdraw action for any other family, so report the finding when a carried family
436/// is known to be something else.
437fn domain_path_family_warning(families: DomainPathFamilies) -> Option<BgpValidationWarning> {
438    families.disallowed().map(|family| {
439        BgpValidationWarning::OptionalAttributeError {
440            attr_type: AttrType::BGP_DOMAIN_PATH,
441            reason: format!(
442                "D-PATH is only valid on IPVPN (AFI 1/2, SAFI 128) or EVPN (AFI 25, SAFI 70) routes, this UPDATE carries {family}: RFC 10039 §4 requires treat-as-withdraw"
443            ),
444        }
445    })
446}
447
448/// Parse BGP attributes given a slice of u8 and some options.
449///
450/// The `data: &[u8]` contains the entirety of the attributes bytes, therefore the size of
451/// the slice is the total byte length of the attributes section of the message.
452pub fn parse_attributes(
453    mut data: Bytes,
454    asn_len: &AsnLength,
455    add_path: bool,
456    afi: Option<Afi>,
457    safi: Option<Safi>,
458    prefixes: Option<&[NetworkPrefix]>,
459) -> Result<Attributes, ParserError> {
460    // Estimate capacity from data size. A wire attribute is at least three bytes (flags, type,
461    // length) and real attributes average far larger, so `len / 3` claimed one slot per three
462    // bytes and over-allocated by an order of magnitude on short records. The floor keeps the
463    // common five-attribute record from growing; the cap keeps a corrupt section from reserving
464    // hundreds of slots. An empty section (withdrawals, End-of-RIB) reserves nothing.
465    let estimated_attrs = if data.is_empty() {
466        0
467    } else {
468        (data.remaining() / 16).clamp(8, 32)
469    };
470    let mut attributes: Vec<Attribute> = Vec::with_capacity(estimated_attrs);
471    let mut validation = AttributeValidationState::new();
472    // A handle on the whole attribute section, so an attribute that fails to parse can be kept
473    // raw by re-slicing it, without cloning every attribute's bytes up front.
474    let section = data.clone();
475
476    while data.remaining() >= 3 {
477        // each attribute is at least 3 bytes: flag(1) + type(1) + length(1)
478        // thus the while loop condition is set to be at least 3 bytes to read.
479
480        // has content to read
481        let flag = AttrFlags::from_bits_retain(data.read_u8()?);
482        let attr_type = data.read_u8()?;
483        let attr_length = match flag.contains(AttrFlags::EXTENDED) {
484            false => data.read_u8()? as usize,
485            true => data.read_u16()? as usize,
486        };
487
488        debug!(
489            "reading attribute: type -- {:?}, length -- {}",
490            attr_type, attr_length
491        );
492
493        let attr_type = AttrType::from(attr_type);
494
495        let partial = validation.observe_header(attr_type.into(), attr_type, flag, attr_length);
496
497        let bytes_left = data.remaining();
498
499        if data.remaining() < attr_length {
500            warn!(
501                "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message",
502                attr_type, attr_length, bytes_left
503            );
504            // break and return already parsed attributes
505            break;
506        }
507
508        // we know data has enough bytes to read, so we can split the bytes into a new Bytes object
509        data.has_n_remaining(attr_length)?;
510        let value_start = section.len() - data.len();
511        let raw_code = u8::from(attr_type);
512
513        // The attributes that make up nearly every record decode from a borrowed slice, which
514        // skips the per-attribute `Bytes` split and its refcount traffic. Each stays in its own
515        // branch: routing them through one dispatcher costs more than the split it saves.
516        let attr = if matches!(attr_type, AttrType::AS_PATH | AttrType::AS4_PATH) {
517            let value = &section[value_start..value_start + attr_length];
518            let path_len = match attr_type {
519                AttrType::AS4_PATH => &AsnLength::Bits32,
520                _ => asn_len,
521            };
522            let parsed = parse_as_path_slice(value, path_len);
523            data.advance(attr_length);
524            parsed.map(|path| match attr_type {
525                AttrType::AS4_PATH => AttributeValue::As4Path(path),
526                _ => AttributeValue::AsPath(path),
527            })
528        } else if attr_type == AttrType::ORIGIN {
529            let value = &section[value_start..value_start + attr_length];
530            data.advance(attr_length);
531            parse_origin(value)
532        } else if attr_type == AttrType::NEXT_HOP {
533            let value = &section[value_start..value_start + attr_length];
534            data.advance(attr_length);
535            parse_next_hop(value, &afi)
536        } else if attr_type == AttrType::MULTI_EXIT_DISCRIMINATOR {
537            let value = &section[value_start..value_start + attr_length];
538            data.advance(attr_length);
539            parse_med(value)
540        } else if attr_type == AttrType::LOCAL_PREFERENCE {
541            let value = &section[value_start..value_start + attr_length];
542            data.advance(attr_length);
543            parse_local_pref(value)
544        } else {
545            let mut attr_data = data.split_to(attr_length);
546
547            if let Some(t) = get_deprecated_attr_type(raw_code) {
548                debug!("deprecated attribute type: {} - {}", raw_code, t);
549                attributes.push(Attribute {
550                    value: AttributeValue::Deprecated(AttrRaw {
551                        code: raw_code,
552                        bytes: attr_data,
553                    }),
554                    flag,
555                });
556                continue;
557            }
558
559            if matches!(attr_type, AttrType::Unknown(_)) {
560                debug!("unknown attribute type: {}", raw_code);
561                attributes.push(Attribute {
562                    value: AttributeValue::Unknown(AttrRaw {
563                        code: raw_code,
564                        bytes: attr_data,
565                    }),
566                    flag,
567                });
568                continue;
569            }
570
571            if is_raw_retained_attr(attr_type) {
572                debug!("raw-retained attribute type: {}", raw_code);
573                attributes.push(Attribute {
574                    value: AttributeValue::Raw(AttrRaw {
575                        code: raw_code,
576                        bytes: attr_data,
577                    }),
578                    flag,
579                });
580                continue;
581            }
582
583            match attr_type {
584                // ORIGIN, NEXT_HOP, MED and LOCAL_PREF are handled above from a borrowed slice.
585                AttrType::ATOMIC_AGGREGATE => Ok(AttributeValue::AtomicAggregate),
586                AttrType::AGGREGATOR => parse_aggregator(attr_data, asn_len)
587                    .map(|(asn, id)| AttributeValue::Aggregator { asn, id }),
588                AttrType::ORIGINATOR_ID => parse_originator_id(attr_data),
589                AttrType::CLUSTER_LIST => parse_clusters(attr_data),
590                AttrType::MP_REACHABLE_NLRI => {
591                    parse_nlri(attr_data, &afi, &safi, &prefixes, true, add_path)
592                }
593                AttrType::MP_UNREACHABLE_NLRI => {
594                    parse_nlri(attr_data, &afi, &safi, &prefixes, false, add_path)
595                }
596                AttrType::AS4_AGGREGATOR => parse_aggregator(attr_data, &AsnLength::Bits32)
597                    .map(|(asn, id)| AttributeValue::As4Aggregator { asn, id }),
598
599                // communities
600                AttrType::COMMUNITIES => parse_regular_communities(attr_data),
601                AttrType::LARGE_COMMUNITIES => parse_large_communities(attr_data),
602                AttrType::EXTENDED_COMMUNITIES => parse_extended_community(attr_data),
603                AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES => {
604                    parse_ipv6_extended_community(attr_data)
605                }
606                AttrType::DEVELOPMENT => {
607                    let mut value = vec![];
608                    for _i in 0..attr_length {
609                        value.push(attr_data.read_u8()?);
610                    }
611                    Ok(AttributeValue::Development(value))
612                }
613                AttrType::ONLY_TO_CUSTOMER => parse_only_to_customer(attr_data),
614                AttrType::AIGP => parse_aigp(attr_data),
615                AttrType::TUNNEL_ENCAPSULATION => parse_tunnel_encapsulation_attribute(attr_data),
616                AttrType::TRAFFIC_ENGINEERING => parse_traffic_engineering(attr_data),
617                AttrType::BGP_LS_ATTRIBUTE => parse_link_state_attribute(attr_data),
618                AttrType::BGP_DOMAIN_PATH => parse_domain_path(attr_data),
619                AttrType::SFP_ATTRIBUTE => parse_sfp(attr_data),
620                AttrType::BFD_DISCRIMINATOR => parse_bfd_discriminator(attr_data),
621                AttrType::BGP_PREFIX_SID => parse_bgp_prefix_sid(attr_data),
622                AttrType::BIER => parse_bier(attr_data),
623                _ => Err(ParserError::Unsupported(format!(
624                    "unsupported attribute type: {attr_type:?}"
625                ))),
626            }
627        };
628
629        match attr {
630            Ok(value) => {
631                assert_eq!(attr_type, value.attr_type());
632                attributes.push(Attribute { value, flag });
633            }
634            Err(e) => {
635                validation.observe_parse_error(attr_type, partial, &e);
636                attributes.push(Attribute {
637                    value: AttributeValue::Raw(AttrRaw {
638                        code: raw_code,
639                        bytes: section.slice(value_start..value_start + attr_length),
640                    }),
641                    flag,
642                });
643                continue;
644            }
645        };
646    }
647
648    let (mut validation_warnings, attr_mask) = validation.finish();
649    if attributes
650        .iter()
651        .any(|attribute| matches!(attribute.value, AttributeValue::DomainPath(_)))
652    {
653        let declared = afi.zip(safi).map(|(afi, safi)| (afi as u16, safi as u8));
654        let families = DomainPathFamilies::from_attributes(&attributes, declared);
655        if let Some(warning) = domain_path_family_warning(families) {
656            validation_warnings.push(warning);
657        }
658    }
659
660    Ok(Attributes {
661        inner: attributes,
662        validation_warnings,
663        attr_mask,
664    })
665}
666
667/// Whether any route in this NLRI carries an ADD-PATH identifier (RFC 7911).
668///
669/// The wire format has no flag for it: the encoder has to infer the state from
670/// the routes themselves, exactly as a decoder is told the state out of band.
671fn has_path_id(nlri: &Nlri) -> bool {
672    nlri.labeled_prefixes
673        .as_ref()
674        .is_some_and(|prefixes| prefixes.iter().any(|p| p.path_id.is_some()))
675        || nlri
676            .evpn_nlris
677            .as_ref()
678            .is_some_and(|routes| routes.iter().any(|r| r.path_id.is_some()))
679}
680
681impl Attribute {
682    /// Append the wire representation of this attribute to `buf`.
683    ///
684    /// The length-field width follows the attribute's EXTENDED_LENGTH flag; a
685    /// value that does not fit the resulting field yields
686    /// [`EncodingError::ValueTooLarge`] instead of being truncated.
687    pub fn encode_to(&self, asn_len: AsnLength, buf: &mut BytesMut) -> Result<(), EncodingError> {
688        buf.put_u8(self.flag.bits());
689        buf.put_u8(self.value.attr_code());
690
691        let write_value = |b: &mut BytesMut| -> Result<(), EncodingError> {
692            match &self.value {
693                AttributeValue::Origin(v) => b.put_slice(&encode_origin(v)),
694                // AS_PATH segment width follows the session's AS number length.
695                AttributeValue::AsPath(path) => {
696                    encode_as_path(path, asn_len, b)?;
697                }
698                // AS4_PATH segments are 4-octet by definition (RFC 6793 §4.2),
699                // independent of the session's AS number length.
700                AttributeValue::As4Path(path) => {
701                    encode_as_path(path, AsnLength::Bits32, b)?;
702                }
703                AttributeValue::NextHop(v) => b.put_slice(&encode_next_hop(v)),
704                AttributeValue::MultiExitDiscriminator(v) => b.put_slice(&encode_med(*v)),
705                AttributeValue::LocalPreference(v) => b.put_slice(&encode_local_pref(*v)),
706                AttributeValue::OnlyToCustomer(v) => {
707                    b.put_slice(&encode_only_to_customer(v.into()))
708                }
709                AttributeValue::AtomicAggregate => {}
710                AttributeValue::Aggregator { asn, id } => {
711                    b.put_slice(&encode_aggregator(asn, &IpAddr::from(*id), asn_len)?)
712                }
713                AttributeValue::As4Aggregator { asn, id } => b.put_slice(&encode_aggregator(
714                    asn,
715                    &IpAddr::from(*id),
716                    AsnLength::Bits32,
717                )?),
718                AttributeValue::Communities(v) => b.put_slice(&encode_regular_communities(v)),
719                AttributeValue::ExtendedCommunities(v) => {
720                    b.put_slice(&encode_extended_communities(v))
721                }
722                AttributeValue::LargeCommunities(v) => b.put_slice(&encode_large_communities(v)),
723                AttributeValue::Ipv6AddressSpecificExtendedCommunities(v) => {
724                    b.put_slice(&encode_ipv6_extended_communities(v))
725                }
726                AttributeValue::OriginatorId(v) => {
727                    b.put_slice(&encode_originator_id(&IpAddr::from(*v)))
728                }
729                AttributeValue::Clusters(v) => b.put_slice(&encode_clusters(v)),
730                AttributeValue::MpReachNlri(v) => {
731                    encode_nlri(v, true, has_path_id(v), b)?;
732                }
733                AttributeValue::MpUnreachNlri(v) => {
734                    // Labeled withdrawals carry plain prefixes (RFC 8277 §2.4),
735                    // but an EVPN withdrawal still carries its ADD-PATH
736                    // identifier, so the state follows the NLRI either way.
737                    encode_nlri(v, false, has_path_id(v), b)?;
738                }
739                AttributeValue::LinkState(v) => encode_link_state_attribute(v, b)?,
740                AttributeValue::TunnelEncapsulation(v) => {
741                    encode_tunnel_encapsulation_attribute(v, b)?
742                }
743                AttributeValue::TrafficEngineering(v) => encode_traffic_engineering(v, b)?,
744                AttributeValue::DomainPath(v) => encode_domain_path(v, b)?,
745                AttributeValue::BfdDiscriminator(v) => encode_bfd_discriminator(v, b)?,
746                AttributeValue::BgpPrefixSid(v) => encode_bgp_prefix_sid(v, b)?,
747                AttributeValue::Bier(v) => encode_bier(v, b)?,
748                AttributeValue::Sfp(v) => encode_sfp(v, b)?,
749                AttributeValue::Development(v) => b.put_slice(v),
750                AttributeValue::Raw(v) => b.put_slice(&v.bytes),
751                AttributeValue::Deprecated(v) => b.put_slice(&v.bytes),
752                AttributeValue::Unknown(v) => b.put_slice(&v.bytes),
753                AttributeValue::Aigp(v) => b.put_slice(&encode_aigp(v)),
754                AttributeValue::AttrSet(_v) => {
755                    return Err(EncodingError::unencodable(
756                        "ATTR_SET attribute",
757                        "encoding not implemented",
758                    ));
759                }
760            }
761            Ok(())
762        };
763
764        match self.is_extended() {
765            false => with_u8_len(buf, "BGP attribute value length", write_value),
766            true => with_u16_len(buf, "BGP attribute value length (extended)", write_value),
767        }
768    }
769
770    /// Encode this attribute into a fresh buffer.
771    pub fn encode(&self, asn_len: AsnLength) -> Result<Bytes, EncodingError> {
772        let mut buf = BytesMut::new();
773        self.encode_to(asn_len, &mut buf)?;
774        Ok(buf.freeze())
775    }
776}
777
778impl Attributes {
779    /// Append the wire representation of all attributes to `buf`.
780    pub fn encode_to(&self, asn_len: AsnLength, buf: &mut BytesMut) -> Result<(), EncodingError> {
781        for attr in &self.inner {
782            attr.encode_to(asn_len, buf)?;
783        }
784        Ok(())
785    }
786
787    /// Encode all attributes into a fresh buffer.
788    pub fn encode(&self, asn_len: AsnLength) -> Result<Bytes, EncodingError> {
789        let mut buf = BytesMut::new();
790        self.encode_to(asn_len, &mut buf)?;
791        Ok(buf.freeze())
792    }
793}
794
795#[cfg(test)]
796mod tests {
797    use super::*;
798
799    #[test]
800    fn test_unknwon_attribute_type() {
801        let data = Bytes::from(vec![0x40, 0xFE, 0x00]);
802        let asn_len = AsnLength::Bits16;
803        let add_path = false;
804        let afi = None;
805        let safi = None;
806        let prefixes = None;
807        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes);
808        assert!(attributes.is_ok());
809        let attributes = attributes.unwrap();
810        assert_eq!(attributes.inner.len(), 1);
811        assert_eq!(
812            attributes.inner[0].value.attr_type(),
813            AttrType::Unknown(254)
814        );
815    }
816
817    #[test]
818    fn test_rfc7606_attribute_flags_error() {
819        // Create an ORIGIN attribute with wrong flags (should be transitive, not optional)
820        let data = Bytes::from(vec![0x80, 0x01, 0x01, 0x00]); // Optional flag set incorrectly
821        let asn_len = AsnLength::Bits16;
822        let add_path = false;
823        let afi = None;
824        let safi = None;
825        let prefixes = None;
826
827        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
828
829        // Should have validation warning for incorrect flags
830        assert!(attributes.has_validation_warnings());
831        let warnings = attributes.validation_warnings();
832        // Will have attribute flags error + missing mandatory attributes
833        assert!(!warnings.is_empty());
834
835        match &warnings[0] {
836            BgpValidationWarning::AttributeFlagsError { attr_type, .. } => {
837                assert_eq!(*attr_type, AttrType::ORIGIN);
838            }
839            _ => panic!("Expected AttributeFlagsError warning"),
840        }
841    }
842
843    #[test]
844    fn test_rfc7606_missing_mandatory_attribute() {
845        // Attributes with only LOCAL_PREF (missing ORIGIN, AS_PATH, NEXT_HOP)
846        let data = Bytes::from(vec![
847            0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x64, // LOCAL_PREF = 100
848        ]);
849        let asn_len = AsnLength::Bits16;
850        let add_path = false;
851        let afi = None;
852        let safi = None;
853        let prefixes = None;
854
855        let mut attributes =
856            parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
857        // Manually trigger mandatory check as an announcement with standard NLRI
858        attributes.check_mandatory_attributes(true, true);
859
860        // Should have warnings for missing mandatory attributes
861        assert!(attributes.has_validation_warnings());
862        let warnings = attributes.validation_warnings();
863        // LOCAL_PREF is not a withdrawal, so ORIGIN, AS_PATH, NEXT_HOP are required
864        assert_eq!(warnings.len(), 3); // ORIGIN, AS_PATH, NEXT_HOP
865
866        for warning in warnings {
867            match warning {
868                BgpValidationWarning::MissingWellKnownAttribute { attr_type } => {
869                    assert!(matches!(
870                        attr_type,
871                        AttrType::ORIGIN | AttrType::AS_PATH | AttrType::NEXT_HOP
872                    ));
873                }
874                _ => panic!("Expected MissingWellKnownAttribute warning"),
875            }
876        }
877    }
878
879    #[test]
880    fn test_mp_reach_no_next_hop() {
881        // Attributes with MP_REACH_NLRI (missing ORIGIN, AS_PATH)
882        // MP_REACH_NLRI is type 14 (0x0E).
883        // We just need a dummy MP_REACH_NLRI.
884        let data = Bytes::from(vec![
885            0x80, 0x0E, 0x06, 0x00, 0x01, 0x01, // AFI=1, SAFI=1
886            0x00, // Next Hop Len = 0 (invalid for parsing, but enough to trigger logic)
887            0x00, // Reserved
888            0x00, // NLRI
889        ]);
890        let asn_len = AsnLength::Bits16;
891        let add_path = false;
892        let afi = None;
893        let safi = None;
894        let prefixes = None;
895
896        let mut attributes =
897            parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
898        // Manually trigger mandatory check as an announcement but NO standard NLRI (MP only)
899        attributes.check_mandatory_attributes(true, false);
900
901        // Should NOT have NEXT_HOP warning because MP_REACH_NLRI is present and has_standard_nlri is false
902        let warnings = attributes.validation_warnings();
903        let has_next_hop_warning = warnings.iter().any(|w| {
904            matches!(
905                w,
906                BgpValidationWarning::MissingWellKnownAttribute {
907                    attr_type: AttrType::NEXT_HOP
908                }
909            )
910        });
911        assert!(!has_next_hop_warning);
912    }
913
914    #[test]
915    fn test_pure_withdrawal_no_warnings() {
916        // Empty attributes - pure withdrawal
917        let data = Bytes::from(vec![]);
918        let asn_len = AsnLength::Bits16;
919        let add_path = false;
920        let afi = None;
921        let safi = None;
922        let prefixes = None;
923
924        let mut attributes =
925            parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
926        // Manually trigger mandatory check as a withdrawal
927        attributes.check_mandatory_attributes(false, false);
928
929        // Should have NO warnings
930        assert!(!attributes.has_validation_warnings());
931
932        // Attributes with only MP_UNREACH_NLRI - pure withdrawal
933        let data = Bytes::from(vec![
934            0x80, 0x0F, 0x03, 0x00, 0x01, 0x01, // AFI=1, SAFI=1
935        ]);
936        let mut attributes =
937            parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
938        attributes.check_mandatory_attributes(false, false);
939        assert!(!attributes.has_validation_warnings());
940    }
941
942    #[test]
943    fn test_rfc7606_duplicate_attribute() {
944        // Create two ORIGIN attributes
945        let data = Bytes::from(vec![
946            0x40, 0x01, 0x01, 0x00, // First ORIGIN attribute
947            0x40, 0x01, 0x01, 0x01, // Second ORIGIN attribute (duplicate)
948        ]);
949        let asn_len = AsnLength::Bits16;
950        let add_path = false;
951        let afi = None;
952        let safi = None;
953        let prefixes = None;
954
955        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
956
957        // Should have warning for duplicate attribute
958        assert!(attributes.has_validation_warnings());
959        let warnings = attributes.validation_warnings();
960
961        // Should have at least one duplicate attribute warning
962        let has_duplicate_warning = warnings
963            .iter()
964            .any(|w| matches!(w, BgpValidationWarning::DuplicateAttribute { .. }));
965        assert!(has_duplicate_warning);
966    }
967
968    #[test]
969    fn test_attribute_type_boundaries() {
970        let asn_len = AsnLength::Bits16;
971        let add_path = false;
972        let afi = None;
973        let safi = None;
974        let prefixes = None;
975
976        // Required attributes for valid BGP message
977        const REQUIRED_ATTRS: &[u8] = &[
978            0x40, 0x01, 0x01, 0x00, // origin
979            0x40, 0x02, 0x00, // as_path
980            0x40, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04, // next_hop
981        ];
982
983        // Test highest (development) attribute type
984        let mut data = REQUIRED_ATTRS.to_vec();
985        data.extend_from_slice(&[0x40, 0xFF, 0x01, 0x00]); // development
986        let data = Bytes::from(data);
987
988        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
989
990        assert!(attributes.has_attr(AttrType::DEVELOPMENT));
991        assert!(!attributes.has_validation_warnings());
992
993        // Test lowest (reserved) attribute type
994        let mut data = REQUIRED_ATTRS.to_vec();
995        data.extend_from_slice(&[0x40, 0x00, 0x01, 0x01]); // reserved
996        let data = Bytes::from(data);
997
998        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
999
1000        assert!(attributes.inner.iter().any(|attr| {
1001            matches!(
1002                &attr.value,
1003                AttributeValue::Raw(raw)
1004                    if raw.code == u8::from(AttrType::RESERVED)
1005                        && raw.bytes == Bytes::from_static(&[0x01])
1006            )
1007        }));
1008        assert!(!attributes.validation_warnings.iter().any(|vw| {
1009            matches!(vw, BgpValidationWarning::OptionalAttributeError { attr_type, reason:_ } if *attr_type == AttrType::RESERVED)
1010        }));
1011    }
1012
1013    #[test]
1014    fn test_raw_retention_for_known_unsupported_attribute() {
1015        let data = Bytes::from(vec![0x80, 0x16, 0x03, 0xaa, 0xbb, 0xcc]); // PMSI_TUNNEL
1016        let attributes =
1017            parse_attributes(data, &AsnLength::Bits16, false, None, None, None).unwrap();
1018
1019        assert_eq!(attributes.inner.len(), 1);
1020        match &attributes.inner[0].value {
1021            AttributeValue::Raw(raw) => {
1022                assert_eq!(raw.code, 22);
1023                assert_eq!(raw.attr_type(), AttrType::PMSI_TUNNEL);
1024                assert_eq!(raw.bytes, Bytes::from_static(&[0xaa, 0xbb, 0xcc]));
1025            }
1026            value => panic!("expected Raw, got {value:?}"),
1027        }
1028        assert_eq!(
1029            attributes.encode(AsnLength::Bits16).unwrap(),
1030            Bytes::from_static(&[0x80, 0x16, 0x03, 0xaa, 0xbb, 0xcc])
1031        );
1032    }
1033
1034    #[test]
1035    fn test_deprecated_code_13_retained_as_deprecated() {
1036        let data = Bytes::from(vec![0x80, 0x0d, 0x04, 0x01, 0x02, 0x03, 0x04]);
1037        let attributes =
1038            parse_attributes(data, &AsnLength::Bits16, false, None, None, None).unwrap();
1039
1040        assert_eq!(attributes.inner.len(), 1);
1041        match &attributes.inner[0].value {
1042            AttributeValue::Deprecated(raw) => {
1043                assert_eq!(raw.code, 13);
1044                assert_eq!(raw.attr_type(), AttrType::Unknown(13));
1045                assert_eq!(raw.bytes, Bytes::from_static(&[0x01, 0x02, 0x03, 0x04]));
1046            }
1047            value => panic!("expected Deprecated, got {value:?}"),
1048        }
1049        assert_eq!(
1050            attributes.encode(AsnLength::Bits16).unwrap(),
1051            Bytes::from_static(&[0x80, 0x0d, 0x04, 0x01, 0x02, 0x03, 0x04])
1052        );
1053    }
1054
1055    #[test]
1056    fn test_malformed_typed_attribute_falls_back_to_raw() {
1057        let data = Bytes::from(vec![0x40, 0x03, 0x03, 0x01, 0x02, 0x03]); // NEXT_HOP length must be 4
1058        let attributes =
1059            parse_attributes(data, &AsnLength::Bits16, false, None, None, None).unwrap();
1060
1061        assert!(attributes.has_validation_warnings());
1062        match &attributes.inner[0].value {
1063            AttributeValue::Raw(raw) => {
1064                assert_eq!(raw.code, 3);
1065                assert_eq!(raw.attr_type(), AttrType::NEXT_HOP);
1066                assert_eq!(raw.bytes, Bytes::from_static(&[0x01, 0x02, 0x03]));
1067            }
1068            value => panic!("expected Raw fallback, got {value:?}"),
1069        }
1070        assert_eq!(
1071            attributes.encode(AsnLength::Bits16).unwrap(),
1072            Bytes::from_static(&[0x40, 0x03, 0x03, 0x01, 0x02, 0x03])
1073        );
1074    }
1075
1076    #[test]
1077    fn test_malformed_attribute_after_others_keeps_its_own_bytes() {
1078        let data = Bytes::from(
1079            [
1080                // ORIGIN IGP
1081                &[0x40, 0x01, 0x01, 0x00][..],
1082                // NEXT_HOP with an extended length of 3 (must be 4)
1083                &[0x50, 0x03, 0x00, 0x03, 0x0a, 0x0b, 0x0c],
1084                // MED 7
1085                &[0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x07],
1086            ]
1087            .concat(),
1088        );
1089        let attributes =
1090            parse_attributes(data, &AsnLength::Bits16, false, None, None, None).unwrap();
1091
1092        assert_eq!(attributes.inner.len(), 3);
1093        assert_eq!(
1094            attributes.inner[0].value,
1095            AttributeValue::Origin(Origin::IGP)
1096        );
1097        match &attributes.inner[1].value {
1098            AttributeValue::Raw(raw) => {
1099                assert_eq!(raw.code, 3);
1100                assert_eq!(raw.bytes, Bytes::from_static(&[0x0a, 0x0b, 0x0c]));
1101            }
1102            value => panic!("expected Raw fallback, got {value:?}"),
1103        }
1104        assert_eq!(
1105            attributes.inner[2].value,
1106            AttributeValue::MultiExitDiscriminator(7)
1107        );
1108    }
1109
1110    #[test]
1111    fn test_all_raw_retained_attribute_codes_parse_and_round_trip() {
1112        let raw_codes = [0, 22, 24, 27, 33, 128];
1113
1114        for code in raw_codes {
1115            let wire = vec![0xc0, code, 0x02, 0xaa, 0xbb];
1116            let attributes = parse_attributes(
1117                Bytes::from(wire.clone()),
1118                &AsnLength::Bits16,
1119                false,
1120                None,
1121                None,
1122                None,
1123            )
1124            .unwrap();
1125            assert_eq!(attributes.inner.len(), 1, "code {code}");
1126            match &attributes.inner[0].value {
1127                AttributeValue::Raw(raw) => {
1128                    assert_eq!(raw.code, code);
1129                    assert_eq!(raw.bytes, Bytes::from_static(&[0xaa, 0xbb]));
1130                }
1131                value => panic!("expected Raw for code {code}, got {value:?}"),
1132            }
1133            assert!(attributes.has_attr(AttrType::from(code)), "code {code}");
1134            assert_eq!(
1135                attributes.encode(AsnLength::Bits16).unwrap(),
1136                Bytes::from(wire)
1137            );
1138        }
1139    }
1140
1141    #[test]
1142    fn test_unassigned_attribute_code_retained_as_unknown() {
1143        let wire = vec![0xc0, 0x7f, 0x02, 0xaa, 0xbb];
1144        let attributes = parse_attributes(
1145            Bytes::from(wire.clone()),
1146            &AsnLength::Bits16,
1147            false,
1148            None,
1149            None,
1150            None,
1151        )
1152        .unwrap();
1153
1154        assert_eq!(attributes.inner.len(), 1);
1155        match &attributes.inner[0].value {
1156            AttributeValue::Unknown(raw) => {
1157                assert_eq!(raw.code, 0x7f);
1158                assert_eq!(raw.attr_type(), AttrType::Unknown(0x7f));
1159                assert_eq!(raw.bytes, Bytes::from_static(&[0xaa, 0xbb]));
1160            }
1161            value => panic!("expected Unknown, got {value:?}"),
1162        }
1163        assert!(attributes.has_attr(AttrType::Unknown(0x7f)));
1164        assert_eq!(
1165            attributes.encode(AsnLength::Bits16).unwrap(),
1166            Bytes::from(wire)
1167        );
1168    }
1169
1170    #[test]
1171    fn test_structured_tlv_attributes_parse_and_round_trip() {
1172        let cases = [
1173            (
1174                vec![0xc0, 0x26, 0x05, 0x01, 0x01, 0x02, 0x03, 0x04],
1175                "BFD Discriminator",
1176            ),
1177            (
1178                vec![0xc0, 0x28, 0x05, 0x7f, 0x00, 0x02, 0xaa, 0xbb],
1179                "BGP Prefix-SID",
1180            ),
1181            (
1182                vec![0xc0, 0x29, 0x06, 0x12, 0x34, 0x00, 0x02, 0xde, 0xad],
1183                "BIER",
1184            ),
1185            (vec![0xc0, 0x25, 0x05, 0x7f, 0x00, 0x02, 0xde, 0xad], "SFP"),
1186            (
1187                vec![
1188                    0xc0, 0x24, 0x0f, // BGP Domain Path, 15-octet value
1189                    0x02, // segment: 2 domains
1190                    0x00, 0x00, 0x00, 0x0A, 0x00, 0x02, 0x80, // ASN 10 / 2 / 128
1191                    0x00, 0x00, 0x00, 0x0B, 0x00, 0x03, 0x46, // ASN 11 / 3 / 70
1192                ],
1193                "BGP Domain Path",
1194            ),
1195        ];
1196
1197        for (wire, name) in cases {
1198            let data = Bytes::from(wire.clone());
1199            let attributes =
1200                parse_attributes(data, &AsnLength::Bits16, false, None, None, None).unwrap();
1201            assert_eq!(attributes.inner.len(), 1, "{name}");
1202            match (name, &attributes.inner[0].value) {
1203                ("BFD Discriminator", AttributeValue::BfdDiscriminator(_))
1204                | ("BGP Prefix-SID", AttributeValue::BgpPrefixSid(_))
1205                | ("BIER", AttributeValue::Bier(_))
1206                | ("SFP", AttributeValue::Sfp(_))
1207                | ("BGP Domain Path", AttributeValue::DomainPath(_)) => {}
1208                (_, value) => panic!("unexpected value for {name}: {value:?}"),
1209            }
1210            assert_eq!(
1211                attributes.encode(AsnLength::Bits16).unwrap(),
1212                Bytes::from(wire),
1213                "{name}"
1214            );
1215        }
1216    }
1217
1218    #[test]
1219    fn test_rfc7606_attribute_length_error() {
1220        // Create an ORIGIN attribute with wrong length (should be 1 byte, not 2)
1221        let data = Bytes::from(vec![0x40, 0x01, 0x02, 0x00, 0x01]);
1222        let asn_len = AsnLength::Bits16;
1223        let add_path = false;
1224        let afi = None;
1225        let safi = None;
1226        let prefixes = None;
1227
1228        let attributes = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes).unwrap();
1229
1230        // Should have warning for incorrect attribute length
1231        assert!(attributes.has_validation_warnings());
1232        let warnings = attributes.validation_warnings();
1233
1234        let has_length_warning = warnings
1235            .iter()
1236            .any(|w| matches!(w, BgpValidationWarning::AttributeLengthError { .. }));
1237        assert!(has_length_warning);
1238    }
1239
1240    #[test]
1241    fn test_rfc7606_no_session_reset() {
1242        // Test that parsing continues even with multiple errors
1243        let data = Bytes::from(vec![
1244            0x80, 0x01, 0x02, 0x00, 0x01, // Wrong flags and length for ORIGIN
1245            0x40, 0x01, 0x01, 0x00, // Duplicate ORIGIN
1246            0x40, 0xFF, 0x01, 0x00, // Unknown attribute
1247        ]);
1248        let asn_len = AsnLength::Bits16;
1249        let add_path = false;
1250        let afi = None;
1251        let safi = None;
1252        let prefixes = None;
1253
1254        // Should not panic or return error - RFC 7606 requires continued parsing
1255        let result = parse_attributes(data, &asn_len, add_path, afi, safi, prefixes);
1256        assert!(result.is_ok());
1257
1258        let attributes = result.unwrap();
1259        assert!(attributes.has_validation_warnings());
1260
1261        // Should have multiple warnings but parsing should continue
1262        let warnings = attributes.validation_warnings();
1263        assert!(!warnings.is_empty());
1264    }
1265
1266    #[test]
1267    fn test_encode_as_path_attribute_type_selection() {
1268        // Regression test for issue #329: an AS_PATH built for a 4-octet
1269        // session must encode as attribute type 2 with 4-octet segments, not
1270        // as AS4_PATH (type 17).
1271        let attrs = Attributes::from_iter(vec![AttributeValue::AsPath(AsPath::from_sequence([
1272            400644,
1273        ]))]);
1274        let buf = attrs.encode(AsnLength::Bits32).unwrap();
1275        assert_eq!(buf[1], 2, "attribute type must be AS_PATH (2)");
1276        // segment header (type 2, count 1) + one 4-octet ASN
1277        assert_eq!(&buf[3..], &[0x02, 0x01, 0x00, 0x06, 0x1D, 0x04]);
1278
1279        // AS4_PATH always encodes as type 17 with 4-octet segments, even on a
1280        // 2-octet session (RFC 6793 §4.2).
1281        let attrs = Attributes::from_iter(vec![AttributeValue::As4Path(AsPath::from_sequence([
1282            400644,
1283        ]))]);
1284        let buf = attrs.encode(AsnLength::Bits16).unwrap();
1285        assert_eq!(buf[1], 17, "attribute type must be AS4_PATH (17)");
1286        assert_eq!(&buf[3..], &[0x02, 0x01, 0x00, 0x06, 0x1D, 0x04]);
1287    }
1288
1289    #[test]
1290    fn test_encode_as_path_on_2octet_session() {
1291        let attrs = Attributes::from_iter(vec![AttributeValue::AsPath(AsPath::from_sequence([
1292            64496, 64497,
1293        ]))]);
1294        let buf = attrs.encode(AsnLength::Bits16).unwrap();
1295        assert_eq!(buf[1], 2);
1296        // segment header (type 2, count 2) + two 2-octet ASNs
1297        assert_eq!(&buf[3..], &[0x02, 0x02, 0xFB, 0xF0, 0xFB, 0xF1]);
1298    }
1299
1300    #[test]
1301    fn test_encode_as_path_rejects_4octet_asn_on_2octet_session() {
1302        // A 4-octet AS number that does not fit a 2-octet segment must be an
1303        // encoding error, not a silent truncation to its low 16 bits.
1304        let attrs = Attributes::from_iter(vec![AttributeValue::AsPath(AsPath::from_sequence([
1305            400644,
1306        ]))]);
1307        let err = attrs.encode(AsnLength::Bits16).unwrap_err();
1308        assert_eq!(
1309            err,
1310            EncodingError::ValueTooLarge {
1311                field: "2-octet AS number in AS_PATH segment",
1312                actual: 400644,
1313                max: 65535,
1314            }
1315        );
1316    }
1317
1318    #[test]
1319    fn test_encode_aggregator_attribute_type_selection() {
1320        let attrs = Attributes::from_iter(vec![AttributeValue::As4Aggregator {
1321            asn: Asn::new_32bit(400644),
1322            id: std::net::Ipv4Addr::new(192, 0, 2, 1),
1323        }]);
1324        let buf = attrs.encode(AsnLength::Bits16).unwrap();
1325        assert_eq!(buf[1], 18, "attribute type must be AS4_AGGREGATOR (18)");
1326        assert_eq!(
1327            buf.len(),
1328            3 + 8,
1329            "value must be a 4-octet ASN plus an IPv4 id"
1330        );
1331    }
1332
1333    #[test]
1334    fn test_encode_aggregator_width_follows_session_not_asn_flag() {
1335        // A 4-octet-flagged Asn holding a value that fits 16 bits must encode
1336        // as 2 octets on a 2-octet session: the session width decides, not the
1337        // Asn's internal flag.
1338        let attrs = Attributes::from_iter(vec![AttributeValue::Aggregator {
1339            asn: Asn::new_32bit(258),
1340            id: std::net::Ipv4Addr::new(10, 0, 0, 1),
1341        }]);
1342        let buf = attrs.encode(AsnLength::Bits16).unwrap();
1343        assert_eq!(buf[1], 7, "attribute type must be AGGREGATOR (7)");
1344        assert_eq!(buf.len(), 3 + 6);
1345        assert_eq!(&buf[3..], &[0x01, 0x02, 10, 0, 0, 1]);
1346    }
1347
1348    #[test]
1349    fn test_parse_attributes_maps_as4_wire_types() {
1350        // AS4_PATH (type 17): optional transitive flag 0xC0, one AS_SEQUENCE
1351        // segment with the 4-octet ASN 400644.
1352        let data = Bytes::from(vec![0xC0, 17, 6, 0x02, 0x01, 0x00, 0x06, 0x1D, 0x04]);
1353        let attributes = parse_attributes(data, &AsnLength::Bits16, false, None, None, None)
1354            .expect("AS4_PATH must parse");
1355        match attributes.get_attr(AttrType::AS4_PATH).unwrap().value {
1356            AttributeValue::As4Path(path) => assert_eq!(
1357                path.to_u32_vec_opt(false).unwrap(),
1358                vec![400644],
1359                "AS4_PATH segments must parse as 4-octet regardless of session length"
1360            ),
1361            other => panic!("expected As4Path variant, got {other:?}"),
1362        }
1363
1364        // AS4_AGGREGATOR (type 18): 4-octet ASN plus an IPv4 id.
1365        let data = Bytes::from(vec![0xC0, 18, 8, 0x00, 0x06, 0x1D, 0x04, 192, 0, 2, 1]);
1366        let attributes = parse_attributes(data, &AsnLength::Bits16, false, None, None, None)
1367            .expect("AS4_AGGREGATOR must parse");
1368        match attributes.get_attr(AttrType::AS4_AGGREGATOR).unwrap().value {
1369            AttributeValue::As4Aggregator { asn, .. } => {
1370                assert_eq!(asn, Asn::new_32bit(400644))
1371            }
1372            other => panic!("expected As4Aggregator variant, got {other:?}"),
1373        }
1374    }
1375}