rustbgpd-wire 0.8.4

BGP message codec — encode/decode OPEN, KEEPALIVE, UPDATE, NOTIFICATION, ROUTE-REFRESH
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
use std::collections::HashSet;
use std::net::IpAddr;

use crate::attribute::{AsPath, AsPathSegment, PathAttribute, attr_error_data};
use crate::capability::Safi;
use crate::constants::{attr_flags, attr_type};
use crate::notification::update_subcode;

/// Error produced by UPDATE attribute validation.
///
/// Contains the NOTIFICATION subcode and data bytes per RFC 4271 §6.3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UpdateError {
    /// NOTIFICATION subcode for this validation error.
    pub subcode: u8,
    /// Raw bytes for the NOTIFICATION data field.
    pub data: Vec<u8>,
}

/// Well-known attribute type codes that MUST be present when NLRI is advertised.
const MANDATORY_ATTRS: &[u8] = &[attr_type::ORIGIN, attr_type::AS_PATH];

/// Validate the semantic correctness of a set of path attributes.
///
/// This is separate from decode (which is structural — "can I read these bytes?").
/// Validation checks whether the attribute set is RFC-compliant for this UPDATE.
///
/// `has_nlri` — true if the UPDATE carries announced prefixes (body or MP).
/// `has_body_nlri` — true if the UPDATE carries IPv4 NLRI in the body fields.
/// `is_ebgp` — true if the session is external BGP.
///
/// # Errors
///
/// Returns an `UpdateError` with the appropriate subcode and data.
pub fn validate_update_attributes(
    attrs: &[PathAttribute],
    has_nlri: bool,
    has_body_nlri: bool,
    is_ebgp: bool,
) -> Result<(), UpdateError> {
    check_duplicate_types(attrs)?;
    check_unrecognized_wellknown(attrs)?;

    if has_nlri {
        check_mandatory_present(attrs, has_body_nlri, is_ebgp)?;
    }

    for attr in attrs {
        match attr {
            PathAttribute::NextHop(addr) => check_next_hop(*addr)?,
            PathAttribute::AsPath(path) => check_as_path(path)?,
            // RFC 8955 §6.1: for FlowSpec (SAFI 133), the NEXT_HOP
            // attribute value is "irrelevant" and is recommended
            // to be 0 when advertising. The on-wire NH-Len for
            // FlowSpec is 0 and the decoder fills `mp.next_hop`
            // with 0.0.0.0; running the standard NEXT_HOP validator
            // (which rejects 0.0.0.0) on a FlowSpec MP_REACH causes
            // us to send NOTIFICATION 3/8 and tear the session
            // against any RFC-compliant peer. Skip validation for
            // FlowSpec; the rule contents travel in
            // `flowspec_announced`, not next_hop.
            PathAttribute::MpReachNlri(mp) if mp.safi != Safi::FlowSpec => {
                check_mp_reach_next_hop(mp.next_hop, mp.link_local_next_hop)?;
            }
            _ => {}
        }
    }

    Ok(())
}

/// (3,1) Duplicate attribute type codes.
fn check_duplicate_types(attrs: &[PathAttribute]) -> Result<(), UpdateError> {
    let mut seen = HashSet::new();
    for attr in attrs {
        let tc = attr.type_code();
        if !seen.insert(tc) {
            return Err(UpdateError {
                subcode: update_subcode::MALFORMED_ATTRIBUTE_LIST,
                data: vec![],
            });
        }
    }
    Ok(())
}

/// (3,2) Unrecognized well-known attribute: Optional=0 and type code unknown.
fn check_unrecognized_wellknown(attrs: &[PathAttribute]) -> Result<(), UpdateError> {
    for attr in attrs {
        if let PathAttribute::Unknown(raw) = attr {
            // If Optional bit is NOT set, it claims to be well-known
            if (raw.flags & attr_flags::OPTIONAL) == 0 {
                return Err(UpdateError {
                    subcode: update_subcode::UNRECOGNIZED_WELLKNOWN,
                    data: attr_error_data(raw.flags, raw.type_code, &raw.data),
                });
            }
        }
    }
    Ok(())
}

/// (3,3) Missing mandatory well-known attributes.
///
/// `has_body_nlri` — true if the UPDATE carries IPv4 NLRI in the body fields.
/// When only `MP_REACH_NLRI` is present (no body NLRI), `NEXT_HOP` is carried
/// inside the MP attribute (RFC 4760 §3) and not required as a separate attribute.
/// Mixed UPDATEs (body NLRI + `MP_REACH_NLRI`) still require body `NEXT_HOP`.
fn check_mandatory_present(
    attrs: &[PathAttribute],
    has_body_nlri: bool,
    is_ebgp: bool,
) -> Result<(), UpdateError> {
    let present: HashSet<u8> = attrs.iter().map(PathAttribute::type_code).collect();

    for &tc in MANDATORY_ATTRS {
        if !present.contains(&tc) {
            return Err(UpdateError {
                subcode: update_subcode::MISSING_WELLKNOWN,
                data: vec![tc],
            });
        }
    }

    // NEXT_HOP mandatory for eBGP when body NLRI is present. When only MP_REACH
    // carries NLRI, the next-hop is inside the MP attribute (RFC 4760 §3).
    if is_ebgp && has_body_nlri && !present.contains(&attr_type::NEXT_HOP) {
        return Err(UpdateError {
            subcode: update_subcode::MISSING_WELLKNOWN,
            data: vec![attr_type::NEXT_HOP],
        });
    }

    Ok(())
}

/// (3,8) Invalid `NEXT_HOP` address.
fn check_next_hop(addr: std::net::Ipv4Addr) -> Result<(), UpdateError> {
    let octets = addr.octets();

    // 0.0.0.0
    if addr.is_unspecified() {
        return Err(UpdateError {
            subcode: update_subcode::INVALID_NEXT_HOP,
            data: octets.to_vec(),
        });
    }

    // 127.0.0.0/8
    if addr.is_loopback() {
        return Err(UpdateError {
            subcode: update_subcode::INVALID_NEXT_HOP,
            data: octets.to_vec(),
        });
    }

    // 224.0.0.0/4 (multicast)
    if addr.is_multicast() {
        return Err(UpdateError {
            subcode: update_subcode::INVALID_NEXT_HOP,
            data: octets.to_vec(),
        });
    }

    // 255.255.255.255
    if addr.is_broadcast() {
        return Err(UpdateError {
            subcode: update_subcode::INVALID_NEXT_HOP,
            data: octets.to_vec(),
        });
    }

    Ok(())
}

/// Validate `MP_REACH_NLRI` next-hop address(es).
///
/// `addr` is the global next-hop (always present in any non-FlowSpec
/// `MP_REACH`). `link_local` is the optional second-16-byte
/// component carried only when the on-wire NH-Len is 32 (RFC 4760
/// §3 / RFC 2545 §3 — the IPv6-with-link-local form). When present,
/// it MUST be in `fe80::/10`; otherwise the peer is sending a
/// malformed `MP_REACH` and we reject with subcode 8 rather than
/// accepting a non-link-local second segment into the receive path
/// where downstream consumers may treat it as if it were
/// link-local.
fn check_mp_reach_next_hop(
    addr: IpAddr,
    link_local: Option<std::net::Ipv6Addr>,
) -> Result<(), UpdateError> {
    match addr {
        IpAddr::V4(v4) => check_next_hop(v4)?,
        IpAddr::V6(v6) => {
            if !is_valid_ipv6_nexthop(&v6) {
                return Err(UpdateError {
                    subcode: update_subcode::INVALID_NEXT_HOP,
                    data: v6.octets().to_vec(),
                });
            }
        }
    }
    if let Some(ll) = link_local
        && !is_ipv6_link_local(&ll)
    {
        return Err(UpdateError {
            subcode: update_subcode::INVALID_NEXT_HOP,
            data: ll.octets().to_vec(),
        });
    }
    Ok(())
}

/// Check if an IPv6 address is link-local (`fe80::/10`).
fn is_ipv6_link_local(addr: &std::net::Ipv6Addr) -> bool {
    (addr.segments()[0] & 0xffc0) == 0xfe80
}

/// Returns `true` if `addr` is a valid IPv6 next-hop for BGP advertisements.
///
/// Rejects unspecified (`::`), loopback (`::1`), multicast (`ff00::/8`),
/// and link-local (`fe80::/10`) addresses.
#[must_use]
pub fn is_valid_ipv6_nexthop(addr: &std::net::Ipv6Addr) -> bool {
    !addr.is_unspecified()
        && !addr.is_loopback()
        && !addr.is_multicast()
        && !is_ipv6_link_local(addr)
}

/// (3,11) Malformed `AS_PATH`.
fn check_as_path(path: &AsPath) -> Result<(), UpdateError> {
    for segment in &path.segments {
        let asns = match segment {
            AsPathSegment::AsSet(asns) | AsPathSegment::AsSequence(asns) => asns,
        };
        if asns.is_empty() {
            return Err(UpdateError {
                subcode: update_subcode::MALFORMED_AS_PATH,
                data: vec![],
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::net::Ipv4Addr;

    use bytes::Bytes;

    use super::*;
    use crate::attribute::{Origin, RawAttribute};

    fn basic_attrs(next_hop: Ipv4Addr) -> Vec<PathAttribute> {
        vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::NextHop(next_hop),
        ]
    }

    #[test]
    fn valid_ebgp_update() {
        let attrs = basic_attrs(Ipv4Addr::new(10, 0, 0, 1));
        assert!(validate_update_attributes(&attrs, true, true, true).is_ok());
    }

    #[test]
    fn valid_ibgp_update_no_next_hop() {
        // iBGP doesn't require NEXT_HOP (it's optional based on the peer)
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
        ];
        assert!(validate_update_attributes(&attrs, true, true, false).is_ok());
    }

    #[test]
    fn withdrawal_only_no_attrs_ok() {
        // No NLRI → no mandatory attributes required
        assert!(validate_update_attributes(&[], false, false, true).is_ok());
    }

    #[test]
    fn reject_duplicate_type() {
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::Origin(Origin::Egp),
        ];
        let err = validate_update_attributes(&attrs, false, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MALFORMED_ATTRIBUTE_LIST);
    }

    #[test]
    fn reject_missing_origin() {
        let attrs = vec![
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::NextHop(Ipv4Addr::new(10, 0, 0, 1)),
        ];
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MISSING_WELLKNOWN);
    }

    #[test]
    fn reject_missing_as_path() {
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::NextHop(Ipv4Addr::new(10, 0, 0, 1)),
        ];
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MISSING_WELLKNOWN);
    }

    #[test]
    fn reject_missing_next_hop_ebgp() {
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
        ];
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MISSING_WELLKNOWN);
        assert_eq!(err.data, vec![attr_type::NEXT_HOP]);
    }

    #[test]
    fn reject_next_hop_unspecified() {
        let attrs = basic_attrs(Ipv4Addr::UNSPECIFIED);
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn reject_next_hop_loopback() {
        let attrs = basic_attrs(Ipv4Addr::LOCALHOST);
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn reject_next_hop_multicast() {
        let attrs = basic_attrs(Ipv4Addr::new(224, 0, 0, 1));
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn reject_next_hop_broadcast() {
        let attrs = basic_attrs(Ipv4Addr::BROADCAST);
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn reject_empty_as_path_segment() {
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![])],
            }),
            PathAttribute::NextHop(Ipv4Addr::new(10, 0, 0, 1)),
        ];
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MALFORMED_AS_PATH);
    }

    #[test]
    fn reject_unrecognized_wellknown() {
        let attrs = vec![PathAttribute::Unknown(RawAttribute {
            flags: attr_flags::TRANSITIVE, // Optional=0 → claims well-known
            type_code: 99,
            data: Bytes::from_static(&[1, 2, 3]),
        })];
        let err = validate_update_attributes(&attrs, false, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::UNRECOGNIZED_WELLKNOWN);
    }

    #[test]
    fn optional_unknown_attribute_ok() {
        let attrs = vec![PathAttribute::Unknown(RawAttribute {
            flags: attr_flags::OPTIONAL | attr_flags::TRANSITIVE,
            type_code: 99,
            data: Bytes::from_static(&[1, 2, 3]),
        })];
        assert!(validate_update_attributes(&attrs, false, false, true).is_ok());
    }

    // --- MP_REACH_NLRI validation tests ---

    #[test]
    fn mp_reach_nlri_no_body_next_hop_required_for_ebgp() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};
        use crate::nlri::{Ipv6Prefix, NlriEntry, Prefix};

        // eBGP UPDATE with MP_REACH_NLRI only (no body NLRI): NEXT_HOP not required
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6("2001:db8::1".parse().unwrap()),
                link_local_next_hop: None,
                announced: vec![NlriEntry {
                    path_id: 0,
                    prefix: Prefix::V6(Ipv6Prefix::new("2001:db8::".parse().unwrap(), 32)),
                }],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        // has_nlri=true, has_body_nlri=false (only MP NLRI), is_ebgp=true
        assert!(validate_update_attributes(&attrs, true, false, true).is_ok());
    }

    #[test]
    fn mixed_update_requires_body_next_hop_for_ebgp() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};
        use crate::nlri::{Ipv6Prefix, NlriEntry, Prefix};

        // eBGP UPDATE with BOTH body NLRI and MP_REACH_NLRI but no NEXT_HOP attr
        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6("2001:db8::1".parse().unwrap()),
                link_local_next_hop: None,
                announced: vec![NlriEntry {
                    path_id: 0,
                    prefix: Prefix::V6(Ipv6Prefix::new("2001:db8::".parse().unwrap(), 32)),
                }],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        // has_nlri=true, has_body_nlri=true (body IPv4 NLRI present), is_ebgp=true
        // → should require NEXT_HOP for the body NLRI
        let err = validate_update_attributes(&attrs, true, true, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::MISSING_WELLKNOWN);
        assert_eq!(err.data, vec![attr_type::NEXT_HOP]);
    }

    #[test]
    fn mp_reach_nlri_reject_unspecified_v6_next_hop() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED),
                link_local_next_hop: None,
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        let err = validate_update_attributes(&attrs, true, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn mp_reach_nlri_reject_link_local_v6_next_hop() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6("fe80::1".parse().unwrap()),
                link_local_next_hop: None,
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        let err = validate_update_attributes(&attrs, true, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn mp_reach_nlri_reject_loopback_v6_next_hop() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6(std::net::Ipv6Addr::LOCALHOST),
                link_local_next_hop: None,
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        let err = validate_update_attributes(&attrs, true, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    #[test]
    fn is_valid_ipv6_nexthop_accepts_global() {
        assert!(super::is_valid_ipv6_nexthop(
            &"2001:db8::1".parse().unwrap()
        ));
    }

    #[test]
    fn is_valid_ipv6_nexthop_rejects_unspecified() {
        assert!(!super::is_valid_ipv6_nexthop(
            &std::net::Ipv6Addr::UNSPECIFIED
        ));
    }

    #[test]
    fn is_valid_ipv6_nexthop_rejects_loopback() {
        assert!(!super::is_valid_ipv6_nexthop(
            &std::net::Ipv6Addr::LOCALHOST
        ));
    }

    #[test]
    fn is_valid_ipv6_nexthop_rejects_link_local() {
        assert!(!super::is_valid_ipv6_nexthop(&"fe80::1".parse().unwrap()));
    }

    #[test]
    fn is_valid_ipv6_nexthop_rejects_multicast() {
        assert!(!super::is_valid_ipv6_nexthop(&"ff02::1".parse().unwrap()));
    }

    #[test]
    fn mp_reach_nlri_reject_multicast_v6_next_hop() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                // ff02::1 is multicast
                next_hop: std::net::IpAddr::V6("ff02::1".parse().unwrap()),
                link_local_next_hop: None,
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        let err = validate_update_attributes(&attrs, true, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    /// Regression: an `MP_REACH` for `FlowSpec` (SAFI 133) with
    /// the recommended-by-RFC-8955-§6.1 next-hop value of 0.0.0.0
    /// must NOT trip `NEXT_HOP` validation. Before the `FlowSpec`
    /// guard, validate ran the standard `check_next_hop` against
    /// every `MP_REACH` next-hop and rejected 0.0.0.0 with subcode
    /// 8 (Invalid `NEXT_HOP`), causing rustbgpd to send
    /// `NOTIFICATION` 3/8 and tear the session against any
    /// RFC-compliant `FlowSpec` peer (FRR, `GoBGP`). M22 was
    /// masking this with long display-path waits that hid the
    /// resulting flap-and-recover cycle.
    #[test]
    fn mp_reach_flowspec_unspecified_next_hop_is_valid() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv4,
                safi: Safi::FlowSpec,
                // RFC 8955 §6.1 recommends 0.0.0.0 for FlowSpec
                // advertisements; on the wire NH-Len is 0 and the
                // decoder defaults this to 0.0.0.0.
                next_hop: std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
                link_local_next_hop: None,
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        // Empty announced + empty body — FlowSpec EoR-equivalent
        // shape FRR sends post-handshake. Must pass validation.
        assert!(
            validate_update_attributes(&attrs, false, false, true).is_ok(),
            "FlowSpec MP_REACH with 0.0.0.0 next-hop must pass — RFC 8955 §6.1 \
             specifies the next-hop value is irrelevant for FlowSpec and \
             recommends 0. The pre-fix path tore sessions against every \
             RFC-compliant FlowSpec peer."
        );
    }

    /// Audit follow-up: an IPv6 `MP_REACH` with NH-Len=32 (the
    /// global-and-link-local form, RFC 4760 §3 / RFC 2545 §3)
    /// where the second 16 bytes are NOT in `fe80::/10` is a
    /// malformed advertisement. The pre-audit validator only
    /// inspected `mp.next_hop` and silently accepted any value at
    /// `mp.link_local_next_hop`, letting a non-link-local second
    /// segment land in the receive path where downstream consumers
    /// may treat it as if it were link-local. Reject with subcode
    /// 8 (Invalid `NEXT_HOP`).
    #[test]
    fn mp_reach_ipv6_invalid_link_local_segment_rejected() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6("2001:db8::1".parse().unwrap()),
                // Second 16 bytes purport to be link-local but are a
                // global address. Should be rejected.
                link_local_next_hop: Some("2001:db8::2".parse().unwrap()),
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        let err = validate_update_attributes(&attrs, false, false, true).unwrap_err();
        assert_eq!(err.subcode, update_subcode::INVALID_NEXT_HOP);
    }

    /// Audit follow-up complement to the above: a properly-formed
    /// 32-byte next-hop (global + actual link-local) must pass.
    /// Pins that the new validation didn't over-reject the legal form.
    #[test]
    fn mp_reach_ipv6_global_plus_link_local_accepted() {
        use crate::attribute::MpReachNlri;
        use crate::capability::{Afi, Safi};

        let attrs = vec![
            PathAttribute::Origin(Origin::Igp),
            PathAttribute::AsPath(AsPath {
                segments: vec![AsPathSegment::AsSequence(vec![65001])],
            }),
            PathAttribute::MpReachNlri(MpReachNlri {
                afi: Afi::Ipv6,
                safi: Safi::Unicast,
                next_hop: std::net::IpAddr::V6("2001:db8::1".parse().unwrap()),
                link_local_next_hop: Some("fe80::1".parse().unwrap()),
                announced: vec![],
                flowspec_announced: vec![],
                evpn_announced: vec![],
            }),
        ];
        assert!(validate_update_attributes(&attrs, false, false, true).is_ok());
    }
}