bgpkit-parser 0.16.0

MRT/BGP/BMP data processing library
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
use crate::bgp::parse_bgp_message;
use crate::models::capabilities::BgpCapabilityType;
use crate::models::*;
use crate::parser::bmp::error::ParserBmpError;
use crate::parser::bmp::messages::BmpPeerType;
use crate::parser::ReadUtils;
use bytes::{Buf, Bytes};
use log::warn;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use std::net::IpAddr;

#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PeerUpNotification {
    pub local_addr: IpAddr,
    pub local_port: u16,
    pub remote_port: u16,
    pub sent_open: BgpMessage,
    pub received_open: BgpMessage,
    pub tlvs: Vec<PeerUpNotificationTlv>,
}

///Type-Length-Value Type
///
/// <https://www.iana.org/assignments/bmp-parameters/bmp-parameters.xhtml#initiation-peer-up-tlvs>
#[derive(Debug, TryFromPrimitive, IntoPrimitive, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u16)]
pub enum PeerUpTlvType {
    String = 0,
    SysDescr = 1,
    SysName = 2,
    VrTableName = 3,
    AdminLabel = 4,
}

#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PeerUpNotificationTlv {
    pub info_type: PeerUpTlvType,
    pub info_len: u16,
    pub info_value: String,
}

pub fn parse_peer_up_notification(
    data: &mut Bytes,
    afi: &Afi,
    asn_len: &AsnLength,
    peer_type: Option<&BmpPeerType>,
) -> Result<PeerUpNotification, ParserBmpError> {
    let local_addr: IpAddr = match afi {
        Afi::Ipv4 => {
            data.has_n_remaining(12)?;
            data.advance(12);
            let ip = data.read_ipv4_address()?;
            ip.into()
        }
        Afi::Ipv6 => data.read_ipv6_address()?.into(),
        Afi::LinkState => {
            // Link-State doesn't use traditional IP addresses for local address
            // Use IPv4 zero address as placeholder
            data.has_n_remaining(12)?;
            data.advance(12);
            std::net::Ipv4Addr::new(0, 0, 0, 0).into()
        }
    };

    let local_port = data.read_u16()?;
    let remote_port = data.read_u16()?;

    // Extract first BGP message with proper boundary
    data.has_n_remaining(19)?; // BGP header
    let bgp1_length = u16::from_be_bytes([data[16], data[17]]) as usize;
    data.has_n_remaining(bgp1_length)?;
    let mut bgp1_data = data.split_to(bgp1_length);
    let sent_open = parse_bgp_message(&mut bgp1_data, false, asn_len)?;

    // Extract second BGP message with proper boundary
    data.has_n_remaining(19)?; // BGP header
    let bgp2_length = u16::from_be_bytes([data[16], data[17]]) as usize;
    data.has_n_remaining(bgp2_length)?;
    let mut bgp2_data = data.split_to(bgp2_length);
    let received_open = parse_bgp_message(&mut bgp2_data, false, asn_len)?;

    // RFC 9069: For Local RIB, the BGP OPEN messages MUST be fabricated
    if let Some(BmpPeerType::LocalRib) = peer_type {
        // Validate that the OPEN messages contain appropriate capabilities for Local RIB
        if let BgpMessage::Open(ref open_msg) = &sent_open {
            let has_multiprotocol_capability = open_msg.opt_params.iter().any(|param| {
                if let ParamValue::Capacities(caps) = &param.param_value {
                    caps.iter()
                        .any(|cap| cap.ty == BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4)
                } else {
                    false
                }
            });
            if !has_multiprotocol_capability {
                warn!("RFC 9069: Local RIB peer up notification should include multiprotocol capabilities in fabricated OPEN messages (parsing Peer Up Notification)");
            }
        }
    }

    let mut tlvs = vec![];
    let mut has_vr_table_name = false;

    while data.remaining() >= 4 {
        let info_type = PeerUpTlvType::try_from(data.read_u16()?)?;
        let info_len = data.read_u16()?;
        let info_value = data.read_n_bytes_to_string(info_len as usize)?;

        // RFC 9069: VrTableName TLV validation for Local RIB
        if let Some(BmpPeerType::LocalRib) = peer_type {
            if info_type == PeerUpTlvType::VrTableName {
                has_vr_table_name = true;
                // RFC 9069: VrTableName MUST be UTF-8 string of 1-255 bytes
                if info_value.is_empty() || info_value.len() > 255 {
                    warn!(
                        "RFC 9069: VrTableName TLV length must be 1-255 bytes, found {} bytes (parsing Peer Up Notification)",
                        info_value.len()
                    );
                }
            }
        }

        tlvs.push(PeerUpNotificationTlv {
            info_type,
            info_len,
            info_value,
        })
    }

    // RFC 9069: Local RIB instances SHOULD include VrTableName TLV
    if let Some(BmpPeerType::LocalRib) = peer_type {
        if !has_vr_table_name {
            warn!("RFC 9069: Local RIB peer up notification should include VrTableName TLV (parsing Peer Up Notification)");
        }
    }
    Ok(PeerUpNotification {
        local_addr,
        local_port,
        remote_port,
        sent_open,
        received_open,
        tlvs,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::capabilities::{BgpCapabilityType, MultiprotocolExtensionsCapability};
    use bytes::BytesMut;
    use std::cell::RefCell;
    use std::net::{IpAddr, Ipv4Addr};
    use std::sync::{Arc, Mutex, Once};

    thread_local! {
        static WARNING_CAPTURE: RefCell<Option<Arc<Mutex<Vec<String>>>>> = const { RefCell::new(None) };
    }

    struct WarningCaptureGuard {
        warnings: Arc<Mutex<Vec<String>>>,
    }

    impl WarningCaptureGuard {
        fn warnings(&self) -> &Arc<Mutex<Vec<String>>> {
            &self.warnings
        }
    }

    impl Drop for WarningCaptureGuard {
        fn drop(&mut self) {
            clear_warning_logger();
        }
    }

    #[test]
    fn test_parse_peer_up_notification() {
        let mut data = BytesMut::new();
        // Assuming setup for test where local address is "10.1.1.1" IPv4
        // local port is 8000, remote port is 9000. Adjust accordingly.
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x01,
            0x01, 0x01,
        ]);
        data.extend_from_slice(&[0x1F, 0x40]); // 8000 in network byte order
        data.extend_from_slice(&[0x23, 0x28]); // 9000 in network byte order

        let bgp_open_message = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 0,
            asn: Default::default(),
            hold_time: 0,
            bgp_identifier: Ipv4Addr::new(0, 0, 0, 0),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp_open_message_bytes = bgp_open_message.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_open_message_bytes);
        data.extend_from_slice(&bgp_open_message_bytes);

        // add tlv
        data.extend_from_slice(&[0x00, 0x01]); // info_type
        data.extend_from_slice(&[0x00, 0x02]); // info_len
        data.extend_from_slice(&[0x00, 0x03]); // info_value

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;

        let result = parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, None);

        match result {
            Ok(peer_notification) => {
                assert_eq!(
                    peer_notification.local_addr,
                    IpAddr::V4(std::net::Ipv4Addr::new(10, 1, 1, 1))
                );
                assert_eq!(peer_notification.local_port, 8000);
                assert_eq!(peer_notification.remote_port, 9000);

                // Continue to check other values from peer_notification like sent_open, received_open, tlvs
                let tlv = peer_notification.tlvs.first().unwrap();
                assert_eq!(tlv.info_type, PeerUpTlvType::SysDescr);
                assert_eq!(tlv.info_len, 2);
                assert_eq!(tlv.info_value, "\u{0}\u{3}");
            }
            Err(_) => {
                panic!("parse_peer_up_notification should return Ok");
            }
        }
    }

    // Helper function to set up warning capture for tests
    fn setup_warning_logger() -> WarningCaptureGuard {
        use log::{Level, Record};

        static LOGGER_INIT: Once = Once::new();

        struct TestLogger;

        impl log::Log for TestLogger {
            fn enabled(&self, metadata: &log::Metadata) -> bool {
                metadata.level() <= Level::Warn
            }

            fn log(&self, record: &Record) {
                if record.level() <= Level::Warn {
                    WARNING_CAPTURE.with(|capture| {
                        if let Some(warnings) = capture.borrow().as_ref() {
                            match warnings.lock() {
                                Ok(mut warnings) => warnings.push(record.args().to_string()),
                                Err(poisoned) => {
                                    poisoned.into_inner().push(record.args().to_string());
                                }
                            }
                        }
                    });
                }
            }

            fn flush(&self) {}
        }

        LOGGER_INIT.call_once(|| {
            log::set_boxed_logger(Box::new(TestLogger)).unwrap();
            log::set_max_level(log::LevelFilter::Warn);
        });

        let warnings = Arc::new(Mutex::new(Vec::new()));
        WARNING_CAPTURE.with(|capture| {
            *capture.borrow_mut() = Some(warnings.clone());
        });
        WarningCaptureGuard { warnings }
    }

    fn clear_warning_logger() {
        WARNING_CAPTURE.with(|capture| {
            *capture.borrow_mut() = None;
        });
    }

    // Note: These tests verify that the parser handles LocalRib validation correctly.
    // The actual warning messages are logged via the `log` crate and would appear
    // in production use. For testing purposes, we verify that parsing succeeds
    // and the code paths are exercised.

    #[test]
    fn test_parse_peer_up_notification_no_warnings() {
        let warnings = setup_warning_logger();

        // Regression test: This test creates a scenario with two consecutive BGP OPEN messages
        // that would have triggered BGP length warnings in the old implementation.
        // The new implementation should parse cleanly without warnings.

        let mut data = BytesMut::new();

        // Local address (IPv4): 192.168.1.1 + ports
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create two different BGP OPEN messages that will be concatenated
        // This test verifies that the boundary extraction fix prevents BGP length warnings

        // First BGP OPEN message
        let bgp1 = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_16bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp1_bytes = bgp1.encode(AsnLength::Bits32);

        // Second BGP OPEN message
        let bgp2 = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_16bit(65002),
            hold_time: 90,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 2),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp2_bytes = bgp2.encode(AsnLength::Bits32);

        // Add both BGP messages consecutively
        data.extend_from_slice(&bgp1_bytes);
        data.extend_from_slice(&bgp2_bytes);

        // Add a TLV (String type, length 8, "TestNode")
        data.extend_from_slice(&[
            0x00, 0x00, // String TLV type
            0x00, 0x08, // length 8
        ]);
        data.extend_from_slice(b"TestNode");

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;

        let result = parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, None);

        // Test should succeed without any BGP length warnings
        assert!(result.is_ok(), "Parsing should succeed without warnings");

        let peer_notification = result.unwrap();
        assert_eq!(
            peer_notification.local_addr,
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))
        );
        assert_eq!(peer_notification.local_port, 179);
        assert_eq!(peer_notification.remote_port, 179);

        // Ensure both BGP messages were parsed correctly with different ASNs
        if let crate::models::BgpMessage::Open(ref open1) = &peer_notification.sent_open {
            assert_eq!(open1.asn, crate::models::Asn::new_16bit(65001));
        } else {
            panic!("sent_open should be an OPEN message");
        }

        if let crate::models::BgpMessage::Open(ref open2) = &peer_notification.received_open {
            assert_eq!(open2.asn, crate::models::Asn::new_16bit(65002));
        } else {
            panic!("received_open should be an OPEN message");
        }

        // Verify TLV was parsed correctly
        assert_eq!(peer_notification.tlvs.len(), 1);
        assert_eq!(peer_notification.tlvs[0].info_type, PeerUpTlvType::String);
        assert_eq!(peer_notification.tlvs[0].info_value, "TestNode");

        // The main assertion: verify no warnings were logged
        let captured_warnings = warnings.warnings().lock().unwrap();
        assert!(
            captured_warnings.is_empty(),
            "Test should not produce warnings, but got: {:?}",
            *captured_warnings
        );
    }

    #[test]
    fn test_parse_peer_up_insufficient_data_first_bgp() {
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x01,
            0x01, 0x01,
        ]);
        data.extend_from_slice(&[0x1F, 0x40]); // local port
        data.extend_from_slice(&[0x23, 0x28]); // remote port

        // Add incomplete first BGP message (only header, no body)
        data.extend_from_slice(&[
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BGP marker
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
            0x40, // Length = 64 bytes (but we won't provide 64 bytes)
            0x01, // OPEN message type
        ]);
        // Missing the remaining 45 bytes of the BGP OPEN message

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let result = parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, None);

        assert!(
            result.is_err(),
            "Should fail with insufficient data for first BGP message"
        );
    }

    #[test]
    fn test_parse_peer_up_insufficient_data_second_bgp() {
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x01,
            0x01, 0x01,
        ]);
        data.extend_from_slice(&[0x1F, 0x40]); // local port
        data.extend_from_slice(&[0x23, 0x28]); // remote port

        // Add complete first BGP message
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: Default::default(),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(0, 0, 0, 0),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);

        // Add incomplete second BGP message (only partial header)
        data.extend_from_slice(&[
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // BGP marker
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00,
            0x30, // Length = 48 bytes
                  // Missing message type and body
        ]);

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let result = parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, None);

        assert!(
            result.is_err(),
            "Should fail with insufficient data for second BGP message"
        );
    }

    #[test]
    fn test_parse_peer_up_excess_data_in_tlvs() {
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x01,
            0x01, 0x01,
        ]);
        data.extend_from_slice(&[0x1F, 0x40]); // local port
        data.extend_from_slice(&[0x23, 0x28]); // remote port

        // Add two complete BGP messages
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: Default::default(),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(0, 0, 0, 0),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        // Add valid TLVs
        data.extend_from_slice(&[0x00, 0x00]); // String TLV
        data.extend_from_slice(&[0x00, 0x04]); // length 4
        data.extend_from_slice(b"Test"); // value

        data.extend_from_slice(&[0x00, 0x00]); // String TLV
        data.extend_from_slice(&[0x00, 0x06]); // length 6
        data.extend_from_slice(b"Router"); // value

        // Add some random extra bytes (should be safely ignored due to TLV parsing logic)
        data.extend_from_slice(&[0x00, 0x01, 0x02]); // Less than 4 bytes, should exit TLV parsing loop

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let result = parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, None);

        // Should succeed - TLV parsing handles excess data gracefully
        assert!(result.is_ok(), "Should handle excess data gracefully");

        let peer_notification = result.unwrap();
        assert_eq!(peer_notification.tlvs.len(), 2); // Should have parsed 2 TLVs
        assert_eq!(peer_notification.tlvs[0].info_type, PeerUpTlvType::String);
        assert_eq!(peer_notification.tlvs[0].info_value, "Test");
        assert_eq!(peer_notification.tlvs[1].info_type, PeerUpTlvType::String);
        assert_eq!(peer_notification.tlvs[1].info_value, "Router");
    }

    #[test]
    fn test_local_rib_without_multiprotocol_capability() {
        // This test verifies that LocalRib peer up notifications without multiprotocol
        // capabilities are parsed successfully. In production, a warning would be logged.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message WITHOUT multiprotocol capabilities (RFC 9069 violation)
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![], // No capabilities
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // In production, a warning would be logged about missing multiprotocol capability
    }

    #[test]
    fn test_local_rib_with_multiprotocol_capability() {
        // This test verifies that LocalRib peer up notifications WITH multiprotocol
        // capabilities are parsed successfully without warnings.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message WITH multiprotocol capabilities (RFC 9069 compliant)
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![OptParam {
                param_type: 2, // capability
                param_len: 6,
                param_value: ParamValue::Capacities(vec![Capability {
                    ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
                    value: CapabilityValue::MultiprotocolExtensions(
                        MultiprotocolExtensionsCapability {
                            afi: Afi::Ipv4,
                            safi: Safi::Unicast,
                        },
                    ),
                }]),
            }],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // No warning should be logged when multiprotocol capability is present
    }

    #[test]
    fn test_local_rib_without_vr_table_name_tlv() {
        // This test verifies that LocalRib peer up notifications without VrTableName TLV
        // are parsed successfully. In production, a warning would be logged.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message with capabilities
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![OptParam {
                param_type: 2, // capability
                param_len: 6,
                param_value: ParamValue::Capacities(vec![Capability {
                    ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
                    value: CapabilityValue::MultiprotocolExtensions(
                        MultiprotocolExtensionsCapability {
                            afi: Afi::Ipv4,
                            safi: Safi::Unicast,
                        },
                    ),
                }]),
            }],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        // Add TLVs but NO VrTableName (RFC 9069 violation)
        data.extend_from_slice(&[0x00, 0x00]); // String TLV
        data.extend_from_slice(&[0x00, 0x04]); // length 4
        data.extend_from_slice(b"Test");

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // In production, a warning would be logged about missing VrTableName TLV
    }

    #[test]
    fn test_local_rib_with_valid_vr_table_name_tlv() {
        // This test verifies that LocalRib peer up notifications with valid VrTableName TLV
        // are parsed successfully without warnings.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message with capabilities
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![OptParam {
                param_type: 2, // capability
                param_len: 6,
                param_value: ParamValue::Capacities(vec![Capability {
                    ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
                    value: CapabilityValue::MultiprotocolExtensions(
                        MultiprotocolExtensionsCapability {
                            afi: Afi::Ipv4,
                            safi: Safi::Unicast,
                        },
                    ),
                }]),
            }],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        // Add VrTableName TLV with valid length (1-255 bytes)
        data.extend_from_slice(&[0x00, 0x03]); // VrTableName TLV type
        data.extend_from_slice(&[0x00, 0x08]); // length 8
        data.extend_from_slice(b"LocalRIB");

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");

        let peer_notification = result.unwrap();
        assert_eq!(peer_notification.tlvs.len(), 1);
        assert_eq!(
            peer_notification.tlvs[0].info_type,
            PeerUpTlvType::VrTableName
        );
        assert_eq!(peer_notification.tlvs[0].info_value, "LocalRIB");
        // No warnings should be logged with valid VrTableName
    }

    #[test]
    fn test_local_rib_with_empty_vr_table_name() {
        // This test verifies that LocalRib peer up notifications with empty VrTableName
        // are parsed successfully. In production, a warning would be logged.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message with capabilities
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![OptParam {
                param_type: 2, // capability
                param_len: 6,
                param_value: ParamValue::Capacities(vec![Capability {
                    ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
                    value: CapabilityValue::MultiprotocolExtensions(
                        MultiprotocolExtensionsCapability {
                            afi: Afi::Ipv4,
                            safi: Safi::Unicast,
                        },
                    ),
                }]),
            }],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        // Add VrTableName TLV with EMPTY value (RFC 9069 violation)
        data.extend_from_slice(&[0x00, 0x03]); // VrTableName TLV type
        data.extend_from_slice(&[0x00, 0x00]); // length 0 (empty)

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // In production, a warning would be logged about invalid VrTableName length
    }

    #[test]
    fn test_local_rib_with_oversized_vr_table_name() {
        // This test verifies that LocalRib peer up notifications with oversized VrTableName
        // are parsed successfully. In production, a warning would be logged.
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message with capabilities
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![OptParam {
                param_type: 2, // capability
                param_len: 6,
                param_value: ParamValue::Capacities(vec![Capability {
                    ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
                    value: CapabilityValue::MultiprotocolExtensions(
                        MultiprotocolExtensionsCapability {
                            afi: Afi::Ipv4,
                            safi: Safi::Unicast,
                        },
                    ),
                }]),
            }],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        // Add VrTableName TLV with oversized value (>255 bytes, RFC 9069 violation)
        let oversized_name = "A".repeat(256);
        data.extend_from_slice(&[0x00, 0x03]); // VrTableName TLV type
        data.extend_from_slice(&[0x01, 0x00]); // length 256
        data.extend_from_slice(oversized_name.as_bytes());

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::LocalRib;

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // In production, a warning would be logged about oversized VrTableName
    }

    #[test]
    fn test_non_local_rib_no_validation() {
        // This test verifies that non-LocalRib peer types don't trigger LocalRib validations
        let mut data = BytesMut::new();

        // Local address setup
        data.extend_from_slice(&[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xA8,
            0x01, 0x01, // 192.168.1.1
            0x00, 0xB3, // local port 179
            0x00, 0xB3, // remote port 179
        ]);

        // Create BGP OPEN message WITHOUT capabilities (but not LocalRib, so no warning)
        let bgp_open = crate::models::BgpMessage::Open(BgpOpenMessage {
            version: 4,
            asn: crate::models::Asn::new_32bit(65001),
            hold_time: 180,
            bgp_identifier: Ipv4Addr::new(192, 168, 1, 1),
            extended_length: false,
            opt_params: vec![],
        });
        let bgp_bytes = bgp_open.encode(AsnLength::Bits32);
        data.extend_from_slice(&bgp_bytes);
        data.extend_from_slice(&bgp_bytes);

        let afi = Afi::Ipv4;
        let asn_len = AsnLength::Bits32;
        let peer_type = BmpPeerType::Global; // Not LocalRib

        let result =
            parse_peer_up_notification(&mut data.freeze(), &afi, &asn_len, Some(&peer_type));

        assert!(result.is_ok(), "Parsing should succeed");
        // No warnings should be logged for non-LocalRib peer types
    }
}