scion-stack 0.5.2

SCION endhost network stack
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
// Copyright 2025 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Integration tests for basic functionality of PocketSCION.

use std::{
    net::{self, IpAddr},
    time::Duration,
};

use bytes::Bytes;
use chrono::Utc;
use pocketscion::topologies::{
    IA132, IA212, PocketScionHandle, UnderlayType, minimal::two_path_topology,
};
use scion_proto::{
    address::{IsdAsn, ScionAddr, SocketAddr},
    packet::{ByEndpoint, FlowId, ScionPacketRaw, ScionPacketScmp, ScionPacketUdp},
    path::DataPlanePath,
    scmp::{ScmpEchoReply, ScmpMessage},
    wire_encoding::WireEncodeVec,
};
use scion_stack::{
    path::manager::traits::PathManager,
    scionstack::{ScionSocketBindError, ScionStackBuilder},
};
use snap_tokens::v0::dummy_snap_token;
use test_log::test;
use tokio::net::UdpSocket;
use tracing::info;

const MS_100: Duration = Duration::from_millis(1000);

// Macro to assert that operation finishes within the given duration.
macro_rules! within_duration {
    ($duration:expr, $result:expr) => {
        tokio::time::timeout($duration, $result)
            .await
            .expect("operation timed out")
    };
}

#[test(tokio::test)]
#[ntest::timeout(5_000)]
async fn test_bind_two_sockets_send_receive_snap() {
    test_bind_two_sockets_send_receive_impl(two_path_topology(UnderlayType::Snap).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(5_000)]
async fn test_bind_two_sockets_send_receive_udp() {
    test_bind_two_sockets_send_receive_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_bind_with_specific_address_snap() {
    test_bind_with_specific_address_impl(two_path_topology(UnderlayType::Snap).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_bind_with_specific_address_udp() {
    test_bind_with_specific_address_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_bind_port_already_in_use_snap() {
    test_bind_port_already_in_use_impl(two_path_topology(UnderlayType::Snap).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_bind_port_already_in_use_udp() {
    test_bind_port_already_in_use_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_quic_endpoint_creation_snap() {
    test_quic_endpoint_creation_impl(two_path_topology(UnderlayType::Snap).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(5_000)]
async fn test_quic_endpoint_creation_udp() {
    test_quic_endpoint_creation_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(5_000)]
async fn test_bind_two_endpoints_socket_already_in_use() {
    let first_endpoint = anapaya_quinn::Endpoint::client(("0.0.0.0:0").parse().unwrap()).unwrap();
    let local_addr = first_endpoint.local_addr().unwrap();
    info!("Local address: {local_addr:?}");
    let second_endpoint = anapaya_quinn::Endpoint::client(local_addr);
    assert!(
        second_endpoint.is_err(),
        "expected error but got {second_endpoint:?}"
    );
    info!("Local address again: {:?}", first_endpoint.local_addr());
}

async fn test_bind_two_sockets_send_receive_impl(ps_handle: PocketScionHandle) {
    let sender_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    let receiver_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA212).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    // Bind sender and receiver sockets
    let sender_socket = sender_stack.bind(None).await.unwrap();
    let sender_addr = sender_socket.local_addr();

    info!("sender socket bound to {sender_addr:?}");

    let receiver_socket = receiver_stack.bind(None).await.unwrap();
    let receiver_addr = receiver_socket.local_addr();

    info!("receiver socket bound to {receiver_addr:?}");

    // Send packet from sender to receiver
    let test_data = Bytes::from("Hello, World!");
    let mut recv_buffer = [0u8; 1024];

    tokio::join!(
        async {
            let (len, source) = receiver_socket.recv_from(&mut recv_buffer).await.unwrap();
            assert_eq!(
                &recv_buffer[..len],
                test_data.as_ref(),
                "receiver should receive packets"
            );
            assert_eq!(
                source, sender_addr,
                "receiver should receive packets from the sender"
            );
        },
        async {
            sender_socket
                .send_to(test_data.as_ref(), receiver_addr)
                .await
                .unwrap_or_else(|_| {
                    panic!("error sending from {sender_addr:?} to {receiver_addr:?}")
                });
        },
    );
}

async fn test_bind_with_specific_address_impl(ps_handle: PocketScionHandle) {
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    let scion_addr = ScionAddr::new(
        *stack.local_ases().first().unwrap(),
        "127.0.0.1".parse::<IpAddr>().unwrap().into(),
    );
    let port = {
        let bind_host = "127.0.0.1".parse().unwrap();
        let sock = UdpSocket::bind(net::SocketAddr::new(bind_host, 0))
            .await
            .unwrap();
        let port = sock.local_addr().unwrap().port();
        drop(sock);
        port
    };
    let specific_addr = SocketAddr::new(scion_addr, port);
    let socket = stack.bind(Some(specific_addr)).await.unwrap();

    assert_eq!(socket.local_addr(), specific_addr);
}

async fn test_bind_port_already_in_use_impl(ps_handle: PocketScionHandle) {
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    // First bind should succeed
    let socket = stack.bind(None).await.unwrap();
    let addr = socket.local_addr();
    info!("First socket address: {addr:?}");

    // Second bind to same port should fail
    let result = stack.bind(Some(addr)).await;
    assert!(
        matches!(result, Err(ScionSocketBindError::PortAlreadyInUse(port)) if port == addr.port()),
        "expected PortAlreadyInUse({}) when binding to same port twice, got {result:?}",
        addr.port()
    );
    // Make sure the socket is only dropped now.
    info!("Socket is still around: {:?}", socket.local_addr());
    drop(socket);
}

async fn test_quic_endpoint_creation_impl(ps_handle: PocketScionHandle) {
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    #[allow(deprecated)]
    let endpoint = stack
        .quic_endpoint(None, anapaya_quinn::EndpointConfig::default(), None, None)
        .await;

    assert!(endpoint.is_ok());
}

/// Test that an SCMP socket receives SCMP messages.
async fn test_scmp_with_port_is_received_scmp_impl(ps_handle: PocketScionHandle) {
    let sender_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build sender SCION stack");

    let receiver_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA212).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build receiver SCION stack");

    let sender = sender_stack.bind_raw(None).await.unwrap();
    let receiver = receiver_stack.bind_scmp(None).await.unwrap();
    let receiver_addr = receiver.local_addr();
    let path_manager = sender_stack.create_path_manager();

    let echo_data = Bytes::from_static(b"ping test data");
    let sequence = 1u16;

    // Create an SCMP echo request
    let path = path_manager
        .path_wait(
            sender.local_addr().isd_asn(),
            receiver_addr.isd_asn(),
            Utc::now(),
        )
        .await
        .unwrap();
    let echo_request = ScionPacketScmp::new(
        ByEndpoint {
            source: sender.local_addr().scion_address(),
            destination: receiver_addr.scion_address(),
        },
        path.data_plane_path,
        ScmpMessage::EchoReply(ScmpEchoReply::new(
            receiver_addr.port(),
            sequence,
            echo_data.clone(),
        )),
    )
    .unwrap();

    tracing::info!(src = %sender.local_addr(), dst = %receiver_addr, "Sending echo reply");

    tokio::join!(
        async {
            // The test SCMP handler should receive the echo request
            match within_duration!(MS_100, receiver.recv_from()) {
                Ok((scmp_msg, src_addr)) => {
                    match scmp_msg {
                        ScmpMessage::EchoReply(rep) => {
                            assert_eq!(rep.identifier, receiver_addr.port());
                            assert_eq!(rep.sequence_number, sequence);
                            assert_eq!(rep.data, echo_data);
                        }
                        _ => panic!("Expected echo reply, got: {:?}", scmp_msg),
                    }
                    assert_eq!(src_addr, sender.local_addr().scion_address());
                }
                Err(e) => {
                    panic!("Error receiving echo reply: {e:?}");
                }
            }
        },
        async {
            within_duration!(MS_100, sender.send(echo_request.into()))
                .expect("error sending echo reply");
        },
    );
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_scmp_with_port_is_received_scmp_udp_impl() {
    test_scmp_with_port_is_received_scmp_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_scmp_with_port_is_received_scmp_snap_impl() {
    test_scmp_with_port_is_received_scmp_impl(two_path_topology(UnderlayType::Snap).await).await;
}

/// Test that a Raw socket receives SCMP messages.
async fn test_scmp_with_port_is_received_raw_impl(ps_handle: PocketScionHandle) {
    let sender_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build sender SCION stack");

    let receiver_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA212).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build receiver SCION stack");

    let sender = sender_stack.bind_raw(None).await.unwrap();
    let receiver = receiver_stack.bind_raw(None).await.unwrap();
    let receiver_addr = receiver.local_addr();
    let path_manager = sender_stack.create_path_manager();

    let echo_data = Bytes::from_static(b"ping test data");
    let sequence = 1u16;

    // Create an SCMP echo reply
    let path = path_manager
        .path_wait(
            sender.local_addr().isd_asn(),
            receiver_addr.isd_asn(),
            Utc::now(),
        )
        .await
        .unwrap();
    let echo_reply = ScionPacketScmp::new(
        ByEndpoint {
            source: sender.local_addr().scion_address(),
            destination: receiver_addr.scion_address(),
        },
        path.data_plane_path,
        ScmpMessage::EchoReply(ScmpEchoReply::new(
            receiver_addr.port(),
            sequence,
            echo_data.clone(),
        )),
    )
    .unwrap();

    tracing::info!(src = %sender.local_addr(), dst = %receiver_addr, "Sending echo reply");

    tokio::join!(
        async {
            // The Raw socket should receive the echo request
            match within_duration!(MS_100, receiver.recv()) {
                Ok(raw) => {
                    let scmp_pkt: ScionPacketScmp = raw.try_into().expect("invalid scmp packet");
                    match scmp_pkt.message {
                        ScmpMessage::EchoReply(rep) => {
                            assert_eq!(rep.identifier, receiver_addr.port());
                            assert_eq!(rep.sequence_number, sequence);
                            assert_eq!(rep.data, echo_data);
                        }
                        _ => panic!("Expected echo reply, got: {:?}", scmp_pkt.message),
                    }
                }
                Err(e) => {
                    panic!("Error receiving echo reply: {e:?}");
                }
            }
        },
        async {
            within_duration!(MS_100, sender.send(echo_reply.into()))
                .expect("error sending echo reply");
        },
    );
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_scmp_with_port_is_received_raw_udp_impl() {
    test_scmp_with_port_is_received_raw_impl(two_path_topology(UnderlayType::Udp).await).await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_scmp_with_port_is_received_raw_snap_impl() {
    test_scmp_with_port_is_received_raw_impl(two_path_topology(UnderlayType::Snap).await).await;
}

/// Creates a raw SCION packet with unknown next_header (67) for local communication.
fn create_unknown_next_header_packet(
    source: ScionAddr,
    destination: ScionAddr,
    payload: Bytes,
) -> ScionPacketRaw {
    ScionPacketRaw::new(
        ByEndpoint {
            source,
            destination,
        },
        DataPlanePath::EmptyPath,
        payload,
        67, // Unknown next_header value
        FlowId::default(),
    )
    .expect("Failed to create raw SCION packet with unknown next_header")
}

/// Sends a raw SCION packet directly to a SCION socket via tokio::UdpSocket.
async fn send_raw_packet_directly(
    packet: ScionPacketRaw,
    target_socket_addr: SocketAddr,
) -> Result<(), std::io::Error> {
    let target_addr = target_socket_addr
        .local_address()
        .expect("Target socket must have a local address");

    let sender_socket = UdpSocket::bind("127.0.0.1:0").await?;
    let packet_bytes = packet.encode_to_bytes_vec().concat();
    sender_socket.send_to(&packet_bytes, target_addr).await?;
    Ok(())
}

/// Test that a UDP socket ignores packets with unknown next_header (67).
async fn test_udp_socket_ignores_unknown_next_header_impl() {
    let ps_handle = two_path_topology(UnderlayType::Udp).await;
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    let receiver_socket = stack.bind(None).await.unwrap();
    let receiver_addr = receiver_socket.local_addr();

    let test_payload = Bytes::from_static(b"unknown next_header test");
    let packet = create_unknown_next_header_packet(
        receiver_addr.scion_address(),
        receiver_addr.scion_address(),
        test_payload,
    );

    // Send the packet directly
    send_raw_packet_directly(packet, receiver_addr)
        .await
        .expect("Failed to send packet directly");

    // The UDP socket should NOT receive the packet (should timeout)
    let mut recv_buffer = [0u8; 1024];
    let result = tokio::time::timeout(
        Duration::from_millis(200),
        receiver_socket.recv_from(&mut recv_buffer),
    )
    .await;
    assert!(
        result.is_err(),
        "UDP socket should ignore packets with unknown next_header, but received a packet"
    );
}

/// Test that an SCMP socket ignores packets with unknown next_header (67).
async fn test_scmp_socket_ignores_unknown_next_header_impl() {
    let ps_handle = two_path_topology(UnderlayType::Udp).await;
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    let receiver_socket = stack.bind_scmp(None).await.unwrap();
    let receiver_addr = receiver_socket.local_addr();

    let test_payload = Bytes::from_static(b"unknown next_header test");
    let packet = create_unknown_next_header_packet(
        receiver_addr.scion_address(),
        receiver_addr.scion_address(),
        test_payload,
    );

    // Send the packet directly
    send_raw_packet_directly(packet, receiver_addr)
        .await
        .expect("Failed to send packet directly");

    // The SCMP socket should NOT receive the packet (should timeout)
    let result =
        tokio::time::timeout(Duration::from_millis(300), receiver_socket.recv_from()).await;
    assert!(
        result.is_err(),
        "SCMP socket should ignore packets with unknown next_header, but received a packet"
    );
}

/// Test that a RAW socket receives packets with unknown next_header (67).
async fn test_raw_socket_receives_unknown_next_header_impl() {
    let ps_handle = two_path_topology(UnderlayType::Udp).await;
    let stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build SCION stack");

    let receiver_socket = stack.bind_raw(None).await.unwrap();
    let receiver_addr = receiver_socket.local_addr();

    let test_payload = Bytes::from_static(b"unknown next_header test");
    let packet = create_unknown_next_header_packet(
        receiver_addr.scion_address(),
        receiver_addr.scion_address(),
        test_payload.clone(),
    );

    tokio::join!(
        async {
            // The RAW socket SHOULD receive the packet
            match within_duration!(MS_100, receiver_socket.recv()) {
                Ok(raw) => {
                    assert_eq!(
                        raw.payload, test_payload,
                        "RAW socket should receive the packet with unknown next_header"
                    );
                    assert_eq!(
                        raw.headers.common.next_header, 67,
                        "Received packet should have next_header=67"
                    );
                }
                Err(e) => {
                    panic!(
                        "RAW socket should receive packets with unknown next_header, but got error: {e:?}"
                    );
                }
            }
        },
        async {
            // Send the packet directly
            within_duration!(MS_100, send_raw_packet_directly(packet, receiver_addr))
                .expect("Failed to send packet directly");
        },
    );
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_udp_socket_ignores_unknown_next_header() {
    test_udp_socket_ignores_unknown_next_header_impl().await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_scmp_socket_ignores_unknown_next_header() {
    test_scmp_socket_ignores_unknown_next_header_impl().await;
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_raw_socket_receives_unknown_next_header() {
    test_raw_socket_receives_unknown_next_header_impl().await;
}

/// Test that AS-local packets are correctly received or filtered.
///
/// Tests:
/// 1. Packet with correct ISD-AS → received
/// 2. Packet with ISD-AS 0-0 (wildcard/unset) → dropped
/// 3. Packet with wrong destination IP → dropped
/// 4. Packet with wrong destination port → dropped
async fn test_as_local_packets_impl(ps_handle: PocketScionHandle) {
    let sender_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build sender SCION stack");

    let receiver_stack = ScionStackBuilder::new()
        .with_endhost_api(ps_handle.endhost_api(IA132).await.unwrap())
        .with_auth_token(dummy_snap_token())
        .build()
        .await
        .expect("build receiver SCION stack");

    let sender_raw = sender_stack.bind_raw(None).await.unwrap();
    let receiver_udp = receiver_stack.bind(None).await.unwrap();

    let sender_addr = sender_raw.local_addr();
    let receiver_addr = receiver_udp.local_addr();

    info!("Sender raw socket: {sender_addr:?}");
    info!("Receiver UDP socket: {receiver_addr:?}");

    let receiver_ip = receiver_addr
        .local_address()
        .expect("receiver must have local address")
        .ip();

    // Helper to create a UDP-over-SCION packet as ScionPacketRaw.
    let local_packet = |dst: SocketAddr, payload: &[u8]| -> ScionPacketRaw {
        ScionPacketUdp::new(
            ByEndpoint {
                source: sender_addr,
                destination: dst,
            },
            DataPlanePath::EmptyPath,
            Bytes::copy_from_slice(payload),
        )
        .expect("create UDP packet")
        .into()
    };

    let mut recv_buf = [0u8; 1024];

    // Test 1: Correct ISD-AS → should be received.
    {
        let payload = b"correct IA";
        let dst = SocketAddr::new(
            ScionAddr::new(IA132, receiver_ip.into()),
            receiver_addr.port(),
        );
        let pkt = local_packet(dst, payload);
        sender_raw.send(pkt).await.unwrap();
        let (len, src) = within_duration!(MS_100, receiver_udp.recv_from(&mut recv_buf)).unwrap();
        assert_eq!(
            &recv_buf[..len],
            payload.as_slice(),
            "should receive packet with correct ISD-AS"
        );
        assert_eq!(src.isd_asn(), sender_addr.isd_asn());
    }

    // Test 2: ISD-AS 0-0 (wildcard/unset) → should be dropped.
    {
        let payload = b"wildcard IA";
        let dst = SocketAddr::new(
            ScionAddr::new(IsdAsn::WILDCARD, receiver_ip.into()),
            receiver_addr.port(),
        );
        let pkt = local_packet(dst, payload);
        let result = sender_raw.send(pkt).await;
        assert!(
            result.is_err(),
            "sending packet with wildcard ISD-AS should fail",
        );
    }

    // Test 3: Wrong destination IP → should be dropped.
    {
        let wrong_ip: IpAddr = "127.0.0.2".parse().unwrap();
        let dst = SocketAddr::new(ScionAddr::new(IA132, wrong_ip.into()), receiver_addr.port());
        let pkt = local_packet(dst, b"wrong ip");
        sender_raw.send(pkt).await.unwrap();
        let result = tokio::time::timeout(
            Duration::from_millis(100),
            receiver_udp.recv_from(&mut recv_buf),
        )
        .await;
        assert!(
            result.is_err(),
            "should not receive packet with wrong destination IP"
        );
    }

    // Test 4: Wrong destination port → should be dropped.
    {
        let wrong_port = receiver_addr.port().wrapping_add(1);
        let dst = SocketAddr::new(receiver_addr.scion_address(), wrong_port);
        let pkt = local_packet(dst, b"wrong port");
        sender_raw.send(pkt).await.unwrap();
        let result = tokio::time::timeout(
            Duration::from_millis(100),
            receiver_udp.recv_from(&mut recv_buf),
        )
        .await;
        assert!(
            result.is_err(),
            "should not receive packet with wrong destination port"
        );
    }
}

#[test(tokio::test)]
#[ntest::timeout(10_000)]
async fn test_as_local_packets() {
    test_as_local_packets_impl(two_path_topology(UnderlayType::Udp).await).await;
}