net-mesh 0.21.0

High-performance, schema-agnostic, backend-agnostic event bus
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
//! NAT-PMP / PCP wire codec + UDP client.
//!
//! RFC 6886 (NAT-PMP) defines the 2-to-16 byte UDP packets the
//! router speaks on port 5351. PCP (RFC 6887) reuses the same
//! wire port and overlaps in the simple request / response
//! shape we use; this module targets NAT-PMP strictly, which
//! most consumer gateways implement as-is.
//!
//! Stage 4b-2 ships:
//!
//! - The pure codec ([`NatPmpRequest`] / [`NatPmpResponse`] /
//!   [`ResultCode`] / `encode_request` / `decode_response`).
//!   Unit-tested in isolation.
//! - [`NatPmpMapper`] — a `PortMapperClient` implementation
//!   bound to an operator-supplied gateway `Ipv4Addr`. Uses
//!   `tokio::net::UdpSocket` for wire I/O; per-call deadline
//!   of 1 s matches
//!   `docs/PORT_MAPPING_PLAN.md` decision 4.
//!
//! Gateway discovery (how to find the router's IP without the
//! operator telling us) is **not** in this module — it's a
//! stage-4b-4 concern for the sequencer. Tests construct
//! `NatPmpMapper` with a known localhost gateway + a mock UDP
//! responder.
//!
//! # Wire format (RFC 6886 §3)
//!
//! All multi-byte integers are big-endian. Addresses are
//! IPv4-only; the protocol has no IPv6 form.
//!
//! ## External-address request (2 bytes)
//!
//! ```text
//! +-------+-------+
//! | ver=0 |  op=0 |
//! +-------+-------+
//! ```
//!
//! ## External-address response (12 bytes)
//!
//! ```text
//! +-------+-------+----------------+
//! | ver=0 | op=128| result_code    |
//! +-------+-------+----------------+
//! | epoch_seconds (u32)            |
//! +--------------------------------+
//! | external_ip (u32 IPv4)         |
//! +--------------------------------+
//! ```
//!
//! ## UDP map request (12 bytes; op=1 UDP, op=2 TCP)
//!
//! ```text
//! +-------+-------+----------------+
//! | ver=0 |  op   |   reserved     |
//! +-------+-------+----------------+
//! | internal_port | external_port  |
//! +---------------+----------------+
//! | lifetime_secs (u32)            |
//! +--------------------------------+
//! ```
//!
//! Set `lifetime=0` to request removal of the mapping.
//!
//! ## UDP map response (16 bytes; op=128+op)
//!
//! ```text
//! +-------+-------+----------------+
//! | ver=0 | op+128| result_code    |
//! +-------+-------+----------------+
//! | epoch_seconds (u32)            |
//! +--------------------------------+
//! | internal_port | mapped_port    |
//! +---------------+----------------+
//! | lifetime_secs (u32)            |
//! +--------------------------------+
//! ```

use parking_lot::Mutex;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::time::Duration;

use async_trait::async_trait;
use bytes::{BufMut, Bytes, BytesMut};
use tokio::net::UdpSocket;

use super::{PortMapperClient, PortMapping, PortMappingError, Protocol};

/// NAT-PMP uses UDP port 5351 on the gateway (RFC 6886 §1.2).
pub const NATPMP_PORT: u16 = 5351;

/// Version byte. NAT-PMP is version 0; PCP is 2.
pub const NATPMP_VERSION: u8 = 0;

/// Opcode 0: external-address request / response.
pub const OP_EXTERNAL_ADDRESS: u8 = 0;
/// Opcode 1: UDP port-map request / response.
pub const OP_MAP_UDP: u8 = 1;
/// Response opcode offset — the server adds 128 to the request
/// opcode (0 → 128, 1 → 129) to distinguish response from
/// re-transmitted request.
pub const RESPONSE_OP_OFFSET: u8 = 128;

/// Per-call deadline for UDP I/O against the gateway. Matches
/// `docs/PORT_MAPPING_PLAN.md` decision 4; the plan notes this
/// is a per-call timeout, not a per-task deadline.
pub const NATPMP_DEADLINE: Duration = Duration::from_secs(1);

/// Length of an encoded external-address request (2 bytes).
pub const EXTERNAL_REQUEST_LEN: usize = 2;

/// Length of an encoded UDP-map request (12 bytes).
pub const MAP_REQUEST_LEN: usize = 12;

/// Length of an encoded external-address response (12 bytes).
pub const EXTERNAL_RESPONSE_LEN: usize = 12;

/// Length of an encoded UDP-map response (16 bytes).
pub const MAP_RESPONSE_LEN: usize = 16;

/// Result code returned by the router on every response. `Success`
/// (0) is the green path; every other variant signals a specific
/// failure the client can surface as a typed
/// [`PortMappingError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultCode {
    /// RFC 6886 code 0 — the request succeeded.
    Success,
    /// Code 1 — the gateway doesn't speak this version of
    /// NAT-PMP (we always send version 0).
    UnsupportedVersion,
    /// Code 2 — the gateway administratively rejected the
    /// request (policy / ACL / port conflict).
    NotAuthorized,
    /// Code 3 — gateway-internal network failure (e.g. it
    /// can't reach its own upstream).
    NetworkFailure,
    /// Code 4 — gateway mapping table is full.
    OutOfResources,
    /// Code 5 — the opcode we sent isn't one this gateway
    /// supports (shouldn't happen for our two ops, but the
    /// spec allows it).
    UnsupportedOpcode,
    /// Any code outside RFC 6886's 0..=5 range. Carries the raw
    /// value so logs can identify the offending code.
    Unknown(u16),
}

impl ResultCode {
    /// Decode a raw `u16` result code.
    pub fn from_u16(raw: u16) -> Self {
        match raw {
            0 => Self::Success,
            1 => Self::UnsupportedVersion,
            2 => Self::NotAuthorized,
            3 => Self::NetworkFailure,
            4 => Self::OutOfResources,
            5 => Self::UnsupportedOpcode,
            other => Self::Unknown(other),
        }
    }

    /// Stable string for logs + metrics. Never localized.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::UnsupportedVersion => "unsupported-version",
            Self::NotAuthorized => "not-authorized",
            Self::NetworkFailure => "network-failure",
            Self::OutOfResources => "out-of-resources",
            Self::UnsupportedOpcode => "unsupported-opcode",
            Self::Unknown(_) => "unknown",
        }
    }

    /// Convert a non-`Success` code into a [`PortMappingError`].
    /// `Success` maps to `Refused("success")` for symmetry — callers
    /// should early-return before calling this on a success code.
    pub fn to_error(self) -> PortMappingError {
        PortMappingError::Refused(self.as_str().to_string())
    }
}

/// Decoded NAT-PMP request. Used internally by the codec tests;
/// the client only emits via [`encode_request`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NatPmpRequest {
    /// Ask the gateway for its external IPv4 address.
    ExternalAddress,
    /// Request a UDP port mapping. `lifetime = 0` asks the
    /// gateway to remove a previously-installed mapping for
    /// this internal port (RFC 6886 §3.3).
    MapUdp {
        /// The internal (LAN-side) UDP port we're asking to map.
        internal_port: u16,
        /// The external (WAN-side) port we'd prefer. Gateway is
        /// free to pick a different value; the granted port
        /// comes back in the response's `mapped_port` field.
        external_port_hint: u16,
        /// Requested lease length in seconds. `0` means
        /// "remove this mapping."
        lifetime: u32,
    },
}

/// Decoded NAT-PMP response. Returned from [`decode_response`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NatPmpResponse {
    /// Response to an `ExternalAddress` request.
    ExternalAddress {
        /// Result code from the router.
        result: ResultCode,
        /// Router's uptime in seconds (RFC 6886's "Seconds
        /// Since Start of Epoch"). Used by clients that want
        /// to detect gateway reboots; we don't track it.
        epoch_seconds: u32,
        /// The gateway's WAN-facing IPv4 address.
        external_ip: Ipv4Addr,
    },
    /// Response to a `MapUdp` request (install or renewal).
    MapUdp {
        /// Result code from the router.
        result: ResultCode,
        /// Router's uptime in seconds.
        epoch_seconds: u32,
        /// Echoed internal port from the request.
        internal_port: u16,
        /// The external port the gateway actually allocated —
        /// may differ from the `external_port_hint` we sent.
        mapped_port: u16,
        /// Granted lifetime in seconds. Often equal to the
        /// requested lifetime; some gateways cap it lower.
        lifetime: u32,
    },
}

/// Encode a request. Output length is exactly
/// [`EXTERNAL_REQUEST_LEN`] or [`MAP_REQUEST_LEN`].
pub fn encode_request(req: &NatPmpRequest) -> Bytes {
    match req {
        NatPmpRequest::ExternalAddress => {
            let mut buf = BytesMut::with_capacity(EXTERNAL_REQUEST_LEN);
            buf.put_u8(NATPMP_VERSION);
            buf.put_u8(OP_EXTERNAL_ADDRESS);
            buf.freeze()
        }
        NatPmpRequest::MapUdp {
            internal_port,
            external_port_hint,
            lifetime,
        } => {
            let mut buf = BytesMut::with_capacity(MAP_REQUEST_LEN);
            buf.put_u8(NATPMP_VERSION);
            buf.put_u8(OP_MAP_UDP);
            buf.put_u16(0); // reserved
            buf.put_u16(*internal_port);
            buf.put_u16(*external_port_hint);
            buf.put_u32(*lifetime);
            debug_assert_eq!(buf.len(), MAP_REQUEST_LEN);
            buf.freeze()
        }
    }
}

/// Decode a response received on the NAT-PMP UDP socket.
/// Returns `None` if the packet is shorter than the minimum
/// response length, has an unknown version, or carries an
/// unrecognized response opcode.
pub fn decode_response(data: &[u8]) -> Option<NatPmpResponse> {
    if data.len() < EXTERNAL_RESPONSE_LEN {
        return None;
    }
    if data[0] != NATPMP_VERSION {
        return None;
    }
    let raw_op = data[1];
    if raw_op < RESPONSE_OP_OFFSET {
        // Server responses MUST set the high bit (offset 128).
        return None;
    }
    let op = raw_op - RESPONSE_OP_OFFSET;
    let result = ResultCode::from_u16(u16::from_be_bytes([data[2], data[3]]));
    let epoch_seconds = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
    match op {
        OP_EXTERNAL_ADDRESS => {
            if data.len() < EXTERNAL_RESPONSE_LEN {
                return None;
            }
            let external_ip = Ipv4Addr::new(data[8], data[9], data[10], data[11]);
            Some(NatPmpResponse::ExternalAddress {
                result,
                epoch_seconds,
                external_ip,
            })
        }
        OP_MAP_UDP => {
            if data.len() < MAP_RESPONSE_LEN {
                return None;
            }
            let internal_port = u16::from_be_bytes([data[8], data[9]]);
            let mapped_port = u16::from_be_bytes([data[10], data[11]]);
            let lifetime = u32::from_be_bytes([data[12], data[13], data[14], data[15]]);
            Some(NatPmpResponse::MapUdp {
                result,
                epoch_seconds,
                internal_port,
                mapped_port,
                lifetime,
            })
        }
        _ => None,
    }
}

// =========================================================================
// NatPmpMapper — the client
// =========================================================================

/// A [`PortMapperClient`] that talks NAT-PMP to a known gateway.
///
/// Stage 4b-2 leaves gateway discovery outside this type —
/// callers supply the gateway IPv4 directly. Stage 4b-4's
/// sequencer owns the discovery logic (parse OS routing table /
/// use a crate like `default-net`) before constructing the
/// mapper.
///
/// Internally uses a fresh `tokio::net::UdpSocket` per call,
/// bound to `0.0.0.0:0`. Per-call deadline is [`NATPMP_DEADLINE`]
/// (1 s). No retransmission — a live gateway responds in
/// tens of milliseconds; a dead one doesn't respond at all.
///
/// Caches the external IPv4 from probe across subsequent
/// install / renew calls so the returned `PortMapping.external`
/// carries the router's public address paired with the mapped
/// port (the map response itself only carries the port).
pub struct NatPmpMapper {
    gateway: Ipv4Addr,
    /// Gateway UDP port. Always [`NATPMP_PORT`] in production —
    /// the field exists so tests can target a mock responder on
    /// an unprivileged port without losing coverage of the real
    /// `round_trip` path (the `connect`-based source-address
    /// filter is the whole point of the spoof-rejection test).
    target_port: u16,
    cached_external: Mutex<Option<Ipv4Addr>>,
}

impl NatPmpMapper {
    /// Construct a mapper targeting `gateway` on UDP port
    /// [`NATPMP_PORT`].
    pub fn new(gateway: Ipv4Addr) -> Self {
        Self {
            gateway,
            target_port: NATPMP_PORT,
            cached_external: Mutex::new(None),
        }
    }

    /// Test-only constructor that lets the caller pin the
    /// gateway port. Production code must keep using
    /// [`NatPmpMapper::new`] so the wire destination stays at
    /// the RFC 6886 port.
    #[cfg(test)]
    pub(crate) fn new_for_test(gateway: Ipv4Addr, target_port: u16) -> Self {
        Self {
            gateway,
            target_port,
            cached_external: Mutex::new(None),
        }
    }

    /// Return the gateway this mapper is bound to.
    pub fn gateway(&self) -> Ipv4Addr {
        self.gateway
    }

    /// Read the cached external IPv4 (the most recent value
    /// seen from a response) without issuing a fresh probe.
    /// Used by install + renew to fill in the `external` field
    /// on the returned `PortMapping`.
    fn cached_external(&self) -> Option<Ipv4Addr> {
        *self.cached_external.lock()
    }

    fn set_cached_external(&self, ip: Ipv4Addr) {
        *self.cached_external.lock() = Some(ip);
    }

    /// Send a request to the gateway and wait for a response,
    /// bounded by [`NATPMP_DEADLINE`]. Returns the raw response
    /// bytes.
    ///
    /// Uses `UdpSocket::connect` to pin the kernel-side accept
    /// filter to `(gateway, NATPMP_PORT)`. Any packet from a
    /// host other than the configured gateway — or from the
    /// gateway but on a different source port — is silently
    /// dropped by the kernel before it reaches `recv`. This
    /// implements RFC 6886 §3.1's mandate that clients
    /// "silently ignore any response from anywhere other than
    /// the gateway IP address on port 5351," and prevents an
    /// on-path attacker from spoofing a fake NAT-PMP success
    /// reply with an attacker-controlled external address that
    /// the mesh would then advertise as its reflex.
    async fn round_trip(&self, request: Bytes) -> Result<Vec<u8>, PortMappingError> {
        let sock = UdpSocket::bind("0.0.0.0:0")
            .await
            .map_err(|e| PortMappingError::Transport(e.to_string()))?;
        let target = SocketAddr::new(IpAddr::V4(self.gateway), self.target_port);
        // Kernel-side source-address filter. After `connect`,
        // `send`/`recv` only talk to `target`; packets from
        // anywhere else are discarded without reaching our
        // userland loop.
        sock.connect(target)
            .await
            .map_err(|e| PortMappingError::Transport(e.to_string()))?;
        sock.send(&request)
            .await
            .map_err(|e| PortMappingError::Transport(e.to_string()))?;

        let mut buf = [0u8; 64];
        let n = match tokio::time::timeout(NATPMP_DEADLINE, sock.recv(&mut buf)).await {
            Ok(Ok(n)) => n,
            Ok(Err(e)) => return Err(PortMappingError::Transport(e.to_string())),
            Err(_) => return Err(PortMappingError::Timeout),
        };
        Ok(buf[..n].to_vec())
    }
}

#[async_trait]
impl PortMapperClient for NatPmpMapper {
    async fn probe(&self) -> Result<(), PortMappingError> {
        // Probe by asking for the external address. Any
        // success-coded response proves NAT-PMP is live on the
        // gateway. Also caches the external IPv4 for later
        // install / renew calls.
        let bytes = self
            .round_trip(encode_request(&NatPmpRequest::ExternalAddress))
            .await?;
        let resp = decode_response(&bytes)
            .ok_or_else(|| PortMappingError::Transport("malformed NAT-PMP response".into()))?;
        match resp {
            NatPmpResponse::ExternalAddress {
                result: ResultCode::Success,
                external_ip,
                ..
            } => {
                self.set_cached_external(external_ip);
                Ok(())
            }
            NatPmpResponse::ExternalAddress { result, .. } => Err(result.to_error()),
            _ => Err(PortMappingError::Transport(
                "unexpected NAT-PMP response opcode".into(),
            )),
        }
    }

    async fn install(
        &self,
        internal_port: u16,
        ttl: Duration,
    ) -> Result<PortMapping, PortMappingError> {
        // Reject zero TTL up-front. Per RFC 6886 §3.3, lifetime=0
        // is the "remove this mapping" wire signal — the same
        // format `remove()` sends. Allowing `ttl == Duration::ZERO`
        // here would silently REMOVE the mapping instead of
        // creating one, and the renewal loop would then propagate
        // `mapping.ttl = ZERO` and keep sending removes
        // ("succeeding" while the router had nothing mapped).
        if ttl.is_zero() {
            return Err(PortMappingError::Transport(
                "NAT-PMP install with ttl=0 would unmap; \
                 caller must supply a non-zero lifetime"
                    .into(),
            ));
        }
        let lifetime = ttl.as_secs().min(u32::MAX as u64) as u32;
        let req = NatPmpRequest::MapUdp {
            internal_port,
            external_port_hint: internal_port,
            lifetime,
        };
        let bytes = self.round_trip(encode_request(&req)).await?;
        let resp = decode_response(&bytes)
            .ok_or_else(|| PortMappingError::Transport("malformed NAT-PMP response".into()))?;
        match resp {
            NatPmpResponse::MapUdp {
                result: ResultCode::Success,
                mapped_port,
                lifetime: granted,
                ..
            } => {
                // External IP comes from the cached probe response.
                // If probe wasn't run (or returned an error that
                // left the cache empty), we refuse to produce a
                // mapping rather than silently substituting
                // `self.gateway` — that field holds the router's
                // *private* LAN address, and publishing it as
                // the mapping's "external" surface would poison
                // the capability announcement with an
                // unroutable-from-outside address.
                //
                // Legitimate callers go through `PortMapperTask`
                // or `SequentialMapper`, both of which probe
                // before install. A direct consumer reaching here
                // without probing is a misuse — surface it as a
                // transport error with a diagnostic so the
                // operator finds the missing step instead of
                // staring at peers that can't reach them.
                let external_ip = self.cached_external().ok_or_else(|| {
                    PortMappingError::Transport(
                        "NAT-PMP install called before successful probe — \
                         external address cache empty, refusing to publish \
                         gateway's private IP as external"
                            .into(),
                    )
                })?;
                Ok(PortMapping {
                    external: SocketAddr::new(IpAddr::V4(external_ip), mapped_port),
                    internal_port,
                    ttl: Duration::from_secs(granted as u64),
                    protocol: Protocol::NatPmp,
                })
            }
            NatPmpResponse::MapUdp { result, .. } => Err(result.to_error()),
            _ => Err(PortMappingError::Transport(
                "unexpected NAT-PMP response opcode".into(),
            )),
        }
    }

    async fn renew(&self, mapping: &PortMapping) -> Result<PortMapping, PortMappingError> {
        // Renewal is a fresh map request with the same internal
        // port — NAT-PMP has no distinct renewal op (§3.2).
        self.install(mapping.internal_port, mapping.ttl).await
    }

    async fn remove(&self, mapping: &PortMapping) {
        // Lifetime=0 is the RFC 6886 §3.3 "drop mapping" signal.
        //
        // Previously fire-and-forget — UDP delivery to the gateway
        // is not the same as gateway-side processing, and some
        // routers refuse `lifetime=0` (or are already torn down on
        // our side) without our knowing. Now we do a *short-deadline*
        // recv (200 ms) so a healthy gateway's ack confirms removal,
        // but a misbehaving one doesn't stall shutdown. On timeout we
        // log a warning so operators can investigate stale mappings;
        // on a successful recv with a non-zero result code, we log
        // the failure verbatim.
        const REMOVE_DEADLINE: std::time::Duration = std::time::Duration::from_millis(200);

        let req = NatPmpRequest::MapUdp {
            internal_port: mapping.internal_port,
            external_port_hint: 0,
            lifetime: 0,
        };
        let sock = match UdpSocket::bind("0.0.0.0:0").await {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!(
                    internal_port = mapping.internal_port,
                    error = %e,
                    "NAT-PMP remove: failed to bind UDP socket — \
                     mapping not revoked, gateway holds it until TTL"
                );
                return;
            }
        };
        let target = SocketAddr::new(IpAddr::V4(self.gateway), self.target_port);
        if let Err(e) = sock.connect(target).await {
            tracing::warn!(
                internal_port = mapping.internal_port,
                error = %e,
                "NAT-PMP remove: connect to gateway failed — \
                 mapping not revoked, gateway holds it until TTL"
            );
            return;
        }
        let bytes = encode_request(&req);
        if let Err(e) = sock.send(&bytes).await {
            tracing::warn!(
                internal_port = mapping.internal_port,
                error = %e,
                "NAT-PMP remove: send to gateway failed — \
                 mapping not revoked, gateway holds it until TTL"
            );
            return;
        }

        let mut buf = [0u8; 16];
        match tokio::time::timeout(REMOVE_DEADLINE, sock.recv(&mut buf)).await {
            Ok(Ok(n)) if n > 0 => {
                // RFC 6886 §3.5: bytes [2..4] is the result code (BE u16).
                // 0 = success.
                if n >= 4 {
                    let result_code = u16::from_be_bytes([buf[2], buf[3]]);
                    if result_code != 0 {
                        tracing::warn!(
                            internal_port = mapping.internal_port,
                            result_code,
                            "NAT-PMP remove: gateway returned non-zero result code"
                        );
                    }
                }
            }
            Ok(Ok(_)) => {
                tracing::warn!(
                    internal_port = mapping.internal_port,
                    "NAT-PMP remove: empty response from gateway"
                );
            }
            Ok(Err(e)) => {
                tracing::warn!(
                    internal_port = mapping.internal_port,
                    error = %e,
                    "NAT-PMP remove: recv error"
                );
            }
            Err(_) => {
                tracing::warn!(
                    internal_port = mapping.internal_port,
                    "NAT-PMP remove: gateway did not ack within {}ms — \
                     mapping may still be live",
                    REMOVE_DEADLINE.as_millis()
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- codec round-trips ----

    #[test]
    fn external_request_encodes_to_two_bytes() {
        let bytes = encode_request(&NatPmpRequest::ExternalAddress);
        assert_eq!(&bytes[..], &[NATPMP_VERSION, OP_EXTERNAL_ADDRESS]);
    }

    #[test]
    fn map_udp_request_encodes_with_big_endian_fields() {
        let req = NatPmpRequest::MapUdp {
            internal_port: 9001,
            external_port_hint: 9001,
            lifetime: 3600,
        };
        let bytes = encode_request(&req);
        assert_eq!(bytes.len(), MAP_REQUEST_LEN);
        assert_eq!(bytes[0], NATPMP_VERSION);
        assert_eq!(bytes[1], OP_MAP_UDP);
        assert_eq!(&bytes[2..4], &[0, 0], "reserved must be zero");
        assert_eq!(u16::from_be_bytes([bytes[4], bytes[5]]), 9001);
        assert_eq!(u16::from_be_bytes([bytes[6], bytes[7]]), 9001);
        assert_eq!(
            u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
            3600
        );
    }

    #[test]
    fn decode_external_address_response() {
        // ver=0, op=128 (response to op 0), result=0,
        // epoch=12345, ip=203.0.113.7
        let mut buf = Vec::with_capacity(EXTERNAL_RESPONSE_LEN);
        buf.push(NATPMP_VERSION);
        buf.push(OP_EXTERNAL_ADDRESS + RESPONSE_OP_OFFSET);
        buf.extend_from_slice(&0u16.to_be_bytes()); // success
        buf.extend_from_slice(&12345u32.to_be_bytes());
        buf.extend_from_slice(&[203, 0, 113, 7]);

        match decode_response(&buf) {
            Some(NatPmpResponse::ExternalAddress {
                result: ResultCode::Success,
                epoch_seconds: 12345,
                external_ip,
            }) => {
                assert_eq!(external_ip, Ipv4Addr::new(203, 0, 113, 7));
            }
            other => panic!("expected ExternalAddress Success, got {other:?}"),
        }
    }

    #[test]
    fn decode_map_udp_response() {
        let mut buf = Vec::with_capacity(MAP_RESPONSE_LEN);
        buf.push(NATPMP_VERSION);
        buf.push(OP_MAP_UDP + RESPONSE_OP_OFFSET);
        buf.extend_from_slice(&0u16.to_be_bytes()); // success
        buf.extend_from_slice(&1234u32.to_be_bytes()); // epoch
        buf.extend_from_slice(&9001u16.to_be_bytes()); // internal
        buf.extend_from_slice(&45678u16.to_be_bytes()); // mapped
        buf.extend_from_slice(&3600u32.to_be_bytes()); // lifetime

        match decode_response(&buf) {
            Some(NatPmpResponse::MapUdp {
                result: ResultCode::Success,
                internal_port: 9001,
                mapped_port: 45678,
                lifetime: 3600,
                ..
            }) => {}
            other => panic!("expected MapUdp Success, got {other:?}"),
        }
    }

    /// Regression for BUG_AUDIT_2026_04_30_CORE.md #113: pre-fix
    /// `install` accepted `ttl == Duration::ZERO` and turned it
    /// into a NAT-PMP `lifetime=0`, which per RFC 6886 §3.3 is
    /// the "remove this mapping" wire signal. The gateway acks
    /// (mapping removed); `install` returned `Ok(...)` which
    /// the caller treated as freshly installed — silent
    /// data-plane failure where peers couldn't reach the node.
    /// Compounded by the renewal loop self-removing on the
    /// next tick.
    ///
    /// Post-fix: `install` rejects zero TTL synchronously
    /// before sending the wire request, so callers see an
    /// explicit error and the gateway is never asked to remove
    /// what we meant to install.
    #[tokio::test]
    async fn install_rejects_zero_ttl_before_sending_wire_request() {
        let gateway = Ipv4Addr::new(10, 0, 0, 1);
        let mapper = NatPmpMapper::new(gateway);

        // Pre-fix: this would send an install request with
        // lifetime=0; the gateway would interpret it as remove
        // and return Ok, leaving the caller with `mapping.ttl =
        // ZERO`. Post-fix: rejected synchronously without any
        // wire I/O.
        let result = mapper.install(9001, Duration::ZERO).await;
        match result {
            Err(PortMappingError::Transport(msg)) => {
                assert!(
                    msg.contains("ttl=0"),
                    "error message should mention ttl=0 (got: {msg})"
                );
            }
            other => panic!(
                "ttl=0 install must reject synchronously with Transport \
                 error, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn decode_result_code_variants() {
        assert_eq!(ResultCode::from_u16(0), ResultCode::Success);
        assert_eq!(ResultCode::from_u16(1), ResultCode::UnsupportedVersion);
        assert_eq!(ResultCode::from_u16(2), ResultCode::NotAuthorized);
        assert_eq!(ResultCode::from_u16(3), ResultCode::NetworkFailure);
        assert_eq!(ResultCode::from_u16(4), ResultCode::OutOfResources);
        assert_eq!(ResultCode::from_u16(5), ResultCode::UnsupportedOpcode);
        assert_eq!(ResultCode::from_u16(42), ResultCode::Unknown(42));
    }

    #[test]
    fn decode_rejects_wrong_version() {
        let mut buf = vec![0u8; EXTERNAL_RESPONSE_LEN];
        buf[0] = 2; // PCP, not NAT-PMP
        buf[1] = OP_EXTERNAL_ADDRESS + RESPONSE_OP_OFFSET;
        assert!(decode_response(&buf).is_none());
    }

    #[test]
    fn decode_rejects_request_opcode() {
        // Server responses MUST have op >= 128. A packet with
        // op=0 (request) should decode as None — could be a
        // spoofed echo or a misconfigured stack.
        let mut buf = vec![0u8; EXTERNAL_RESPONSE_LEN];
        buf[0] = NATPMP_VERSION;
        buf[1] = OP_EXTERNAL_ADDRESS; // no +128
        assert!(decode_response(&buf).is_none());
    }

    #[test]
    fn decode_rejects_truncated_response() {
        let buf = vec![NATPMP_VERSION, OP_EXTERNAL_ADDRESS + RESPONSE_OP_OFFSET];
        assert!(decode_response(&buf).is_none());
    }

    #[test]
    fn decode_rejects_truncated_map_response() {
        // Map response needs 16 bytes; 12 looks like an external
        // response but with op=129 (OP_MAP_UDP+128).
        let mut buf = vec![0u8; 12];
        buf[0] = NATPMP_VERSION;
        buf[1] = OP_MAP_UDP + RESPONSE_OP_OFFSET;
        assert!(decode_response(&buf).is_none());
    }

    #[test]
    fn decode_rejects_unknown_opcode() {
        let mut buf = vec![0u8; MAP_RESPONSE_LEN];
        buf[0] = NATPMP_VERSION;
        buf[1] = RESPONSE_OP_OFFSET + 42; // 170 — not defined
        assert!(decode_response(&buf).is_none());
    }

    /// Regression test for TEST_COVERAGE_PLAN §P2-12: the
    /// decoder must never panic on malformed input. A gateway
    /// responding with a truncated / corrupted packet (stack
    /// bug, MTU clip, malicious on-path tamper, or just cosmic
    /// rays) must surface as a clean `None` so the caller falls
    /// back to UPnP or propagates `Transport` cleanly. Pins that
    /// every byte access inside `decode_response` is bounds-
    /// checked.
    ///
    /// Table-driven over all lengths 0..=32 (covers both below
    /// `EXTERNAL_RESPONSE_LEN` and above `MAP_RESPONSE_LEN`),
    /// with three byte patterns chosen to trip different
    /// validation branches (all-zero → wrong op, all-`0xFF` →
    /// version + op + magic values, ascending → potentially
    /// valid prefix with truncated tail). Each combination must
    /// return either `Some(_)` or `None`, never panic.
    #[test]
    fn decode_response_never_panics_on_malformed_input() {
        for len in 0..=32 {
            // All zeros: version=0, op=0, which violates the
            // "op must have high bit set" rule → None.
            let zeros = vec![0u8; len];
            let _ = decode_response(&zeros);

            // All 0xFF: version=255 ≠ 0 → None.
            let ones = vec![0xFFu8; len];
            let _ = decode_response(&ones);

            // Ascending bytes 0..len — has a valid version byte
            // at [0]=0, some op at [1] that MAY or may not look
            // like a response, and whatever the rest lands on.
            let ascending: Vec<u8> = (0..len).map(|i| i as u8).collect();
            let _ = decode_response(&ascending);

            // Descending bytes — different magic / op layout.
            let descending: Vec<u8> = (0..len).map(|i| (255 - i) as u8).collect();
            let _ = decode_response(&descending);
        }

        // Explicit edge case: a response that claims to be a
        // MAP-UDP reply (op = 0x81) but is only 12 bytes long
        // (EXTERNAL_RESPONSE_LEN, not MAP_RESPONSE_LEN). The
        // op-specific inner length check must reject without
        // indexing past the buffer end.
        let mut short_map = vec![0u8; EXTERNAL_RESPONSE_LEN];
        short_map[0] = NATPMP_VERSION;
        short_map[1] = OP_MAP_UDP + RESPONSE_OP_OFFSET;
        assert!(decode_response(&short_map).is_none());
    }

    // ---- live UdpSocket round-trip against a mock gateway ----

    /// Spawn a tokio task that binds a local UDP socket and plays
    /// the role of a NAT-PMP gateway: for each incoming request,
    /// decode it, call `respond`, and send back the returned
    /// bytes. Returns the port the mock bound to.
    async fn spawn_mock_gateway<F>(respond: F) -> (u16, tokio::task::JoinHandle<()>)
    where
        F: Fn(&[u8]) -> Option<Vec<u8>> + Send + Sync + 'static,
    {
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let port = sock.local_addr().unwrap().port();
        let handle = tokio::spawn(async move {
            let mut buf = [0u8; 64];
            loop {
                match sock.recv_from(&mut buf).await {
                    Ok((n, from)) => {
                        if let Some(reply) = respond(&buf[..n]) {
                            let _ = sock.send_to(&reply, from).await;
                        }
                    }
                    Err(_) => return,
                }
            }
        });
        (port, handle)
    }

    /// Wrapper that overrides the target port on `NatPmpMapper`
    /// so tests can point it at the mock gateway's ephemeral
    /// port instead of 5351 (which requires root on unix). Only
    /// exposes `round_trip` — the send-then-receive path — so
    /// we can exercise the deadline + codec end-to-end against
    /// a mock responder without needing a privileged socket.
    struct TestMapper {
        gateway_port: u16,
    }

    impl TestMapper {
        fn new(gateway_port: u16) -> Self {
            Self { gateway_port }
        }

        async fn round_trip(&self, request: Bytes) -> Result<Vec<u8>, PortMappingError> {
            let sock = UdpSocket::bind("127.0.0.1:0")
                .await
                .map_err(|e| PortMappingError::Transport(e.to_string()))?;
            let target: SocketAddr = format!("127.0.0.1:{}", self.gateway_port).parse().unwrap();
            sock.send_to(&request, target)
                .await
                .map_err(|e| PortMappingError::Transport(e.to_string()))?;
            let mut buf = [0u8; 64];
            let (n, _from) =
                match tokio::time::timeout(NATPMP_DEADLINE, sock.recv_from(&mut buf)).await {
                    Ok(Ok(r)) => r,
                    Ok(Err(e)) => return Err(PortMappingError::Transport(e.to_string())),
                    Err(_) => return Err(PortMappingError::Timeout),
                };
            Ok(buf[..n].to_vec())
        }
    }

    /// Trivial helper: encode a success external-address
    /// response with the given IPv4.
    fn encode_external_success(ip: Ipv4Addr) -> Vec<u8> {
        let mut buf = Vec::with_capacity(EXTERNAL_RESPONSE_LEN);
        buf.push(NATPMP_VERSION);
        buf.push(OP_EXTERNAL_ADDRESS + RESPONSE_OP_OFFSET);
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u32.to_be_bytes());
        buf.extend_from_slice(&ip.octets());
        buf
    }

    fn encode_map_success(internal: u16, mapped: u16, lifetime: u32) -> Vec<u8> {
        let mut buf = Vec::with_capacity(MAP_RESPONSE_LEN);
        buf.push(NATPMP_VERSION);
        buf.push(OP_MAP_UDP + RESPONSE_OP_OFFSET);
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u32.to_be_bytes());
        buf.extend_from_slice(&internal.to_be_bytes());
        buf.extend_from_slice(&mapped.to_be_bytes());
        buf.extend_from_slice(&lifetime.to_be_bytes());
        buf
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn nat_pmp_mapper_probe_times_out_against_dead_gateway() {
        // Construct the real `NatPmpMapper` against a gateway
        // port with a bound-but-silent listener. Verifies the
        // full `PortMapperClient::probe` path (encode → UDP
        // send → await response → deadline) without needing a
        // mock that simulates success.
        //
        // Subtlety: after the RFC 6886 §3.1 spoof-rejection
        // fix, `round_trip` calls `UdpSocket::connect(gateway)`.
        // On loopback, sending to a *closed* port surfaces an
        // ICMP destination-unreachable as ECONNREFUSED —
        // `recv` returns `Err` immediately instead of waiting
        // for the deadline. That's correct kernel behavior,
        // just not the "silent gateway" case we want to test.
        // Binding a real socket (that never replies) keeps the
        // port "alive" so the deadline path is what fires.
        let silent = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let silent_port = silent.local_addr().unwrap().port();
        let mapper = NatPmpMapper::new_for_test(Ipv4Addr::LOCALHOST, silent_port);
        assert_eq!(mapper.gateway(), Ipv4Addr::LOCALHOST);

        let start = tokio::time::Instant::now();
        let res = mapper.probe().await;
        let elapsed = start.elapsed();

        assert!(
            matches!(res, Err(PortMappingError::Timeout)),
            "expected Timeout, got {res:?}",
        );
        assert!(
            elapsed >= Duration::from_millis(800) && elapsed < Duration::from_millis(2000),
            "deadline should be ~1 s; got {elapsed:?}",
        );

        // No response → cache stays empty.
        assert!(mapper.cached_external().is_none());
        drop(silent);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn round_trip_times_out_when_gateway_silent() {
        // Bind a socket but don't respond. The mapper's
        // NATPMP_DEADLINE should fire.
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let port = sock.local_addr().unwrap().port();
        // Don't even spawn a receive loop — the request lands
        // and nothing replies.

        let mapper = TestMapper::new(port);
        let start = tokio::time::Instant::now();
        let res = mapper
            .round_trip(encode_request(&NatPmpRequest::ExternalAddress))
            .await;
        let elapsed = start.elapsed();

        assert!(matches!(res, Err(PortMappingError::Timeout)));
        // Deadline is 1 s; allow +/- 200 ms for scheduler jitter.
        assert!(
            elapsed >= Duration::from_millis(800) && elapsed < Duration::from_millis(2000),
            "expected ~1 s timeout, got {elapsed:?}",
        );
        drop(sock);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn probe_against_mock_gateway_returns_success() {
        let (port, gw) = spawn_mock_gateway(|req| {
            let decoded = req.to_vec();
            if decoded == vec![NATPMP_VERSION, OP_EXTERNAL_ADDRESS] {
                Some(encode_external_success(Ipv4Addr::new(198, 51, 100, 7)))
            } else {
                None
            }
        })
        .await;

        // We can't use NatPmpMapper directly because it
        // hard-codes port 5351 on the gateway. Reimplement the
        // probe flow against the mock's port to verify the
        // codec handshake end-to-end.
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let target: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
        sock.send_to(&encode_request(&NatPmpRequest::ExternalAddress), target)
            .await
            .unwrap();
        let mut buf = [0u8; 64];
        let (n, _) = tokio::time::timeout(Duration::from_secs(1), sock.recv_from(&mut buf))
            .await
            .expect("gateway response")
            .unwrap();
        let resp = decode_response(&buf[..n]).expect("decode");

        match resp {
            NatPmpResponse::ExternalAddress {
                result: ResultCode::Success,
                external_ip,
                ..
            } => {
                assert_eq!(external_ip, Ipv4Addr::new(198, 51, 100, 7));
            }
            other => panic!("unexpected response {other:?}"),
        }
        gw.abort();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn install_against_mock_gateway_returns_mapping() {
        let (port, gw) = spawn_mock_gateway(|req| match req {
            // External-address probe → success
            r if r == [NATPMP_VERSION, OP_EXTERNAL_ADDRESS] => {
                Some(encode_external_success(Ipv4Addr::new(198, 51, 100, 7)))
            }
            // Map-UDP install → success with mapped port 54321
            r if r.len() == MAP_REQUEST_LEN && r[0] == NATPMP_VERSION && r[1] == OP_MAP_UDP => {
                let internal = u16::from_be_bytes([r[4], r[5]]);
                Some(encode_map_success(internal, 54321, 3600))
            }
            _ => None,
        })
        .await;

        // Full probe + install flow through the mock port.
        let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let target: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();

        // Probe first.
        sock.send_to(&encode_request(&NatPmpRequest::ExternalAddress), target)
            .await
            .unwrap();
        let mut buf = [0u8; 64];
        let (n, _) = tokio::time::timeout(Duration::from_secs(1), sock.recv_from(&mut buf))
            .await
            .unwrap()
            .unwrap();
        let probe_ip = match decode_response(&buf[..n]).unwrap() {
            NatPmpResponse::ExternalAddress {
                result: ResultCode::Success,
                external_ip,
                ..
            } => external_ip,
            other => panic!("probe failure {other:?}"),
        };
        assert_eq!(probe_ip, Ipv4Addr::new(198, 51, 100, 7));

        // Install.
        let install_req = NatPmpRequest::MapUdp {
            internal_port: 9001,
            external_port_hint: 9001,
            lifetime: 3600,
        };
        sock.send_to(&encode_request(&install_req), target)
            .await
            .unwrap();
        let (n, _) = tokio::time::timeout(Duration::from_secs(1), sock.recv_from(&mut buf))
            .await
            .unwrap()
            .unwrap();
        let mapping = match decode_response(&buf[..n]).unwrap() {
            NatPmpResponse::MapUdp {
                result: ResultCode::Success,
                internal_port: 9001,
                mapped_port: 54321,
                lifetime: 3600,
                ..
            } => (9001u16, 54321u16),
            other => panic!("install failure {other:?}"),
        };
        assert_eq!(mapping, (9001, 54321));
        gw.abort();
    }

    /// Regression test for a cubic-flagged P1 bug: the NAT-PMP
    /// client accepted UDP responses from any source host/port,
    /// letting an on-path attacker inject a fake success with an
    /// attacker-chosen `external_ip`. The mesh would then
    /// advertise that IP as its reflex, poisoning rendezvous
    /// targets.
    ///
    /// RFC 6886 §3.1 requires clients to "silently ignore any
    /// response from anywhere other than the gateway IP address
    /// on port 5351." We implement that by calling
    /// `UdpSocket::connect(gateway, target_port)` before
    /// `recv` — the kernel drops packets from any other
    /// `(ip, port)` pair before they reach userland.
    ///
    /// # Topology
    ///
    /// - **Gateway (silent):** binds an ephemeral loopback port.
    ///   Swallows incoming requests without replying. Its port
    ///   is what `NatPmpMapper::new_for_test` targets, so the
    ///   connected socket's filter pins to that `(127.0.0.1, port)`.
    /// - **Spoofer:** binds a *different* ephemeral loopback
    ///   port. Watches the gateway's mailbox for the client's
    ///   source address (which the spoofer can observe because
    ///   the request went to the gateway, not to it — so we hand
    ///   it the client's source explicitly via a channel the
    ///   spoofer listens on), then races to send a forged
    ///   external-address success from its own source port to
    ///   the client.
    ///
    /// Simpler variant used here: the spoofer just blasts a
    /// fake success to every ephemeral port in a tight range
    /// around the mapper's likely source. Loopback is fast
    /// enough that within the 1-second deadline the spoof
    /// *would* land if the filter weren't working — the
    /// pre-fix code accepted the first matching packet
    /// regardless of source.
    ///
    /// # Assertion
    ///
    /// `probe()` times out (no packet passed the kernel filter)
    /// and the cache stays empty. Without the `connect` call
    /// the spoofed response would reach userland, decode as
    /// success, and populate `cached_external` with the
    /// attacker IP.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn round_trip_rejects_response_from_non_gateway_source() {
        // Silent gateway — binds but never replies.
        let gateway_sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let gateway_port = gateway_sock.local_addr().unwrap().port();

        // Spoofer on a different ephemeral port. When the
        // spoofer sees *anything*, it replies with a fake
        // success. But we have no way to know the mapper's
        // source port in advance — so instead we arrange for
        // the gateway to forward incoming `(source_addr)`
        // tuples to the spoofer over a channel, and the spoofer
        // then sends the forged response back to that exact
        // source port. This makes the spoof as directly
        // targeted as possible — the only remaining defense is
        // the `connect`-based filter on the mapper's socket.
        let (src_tx, mut src_rx) = tokio::sync::mpsc::unbounded_channel::<SocketAddr>();
        let gateway_handle = tokio::spawn(async move {
            let mut buf = [0u8; 64];
            while let Ok((_n, from)) = gateway_sock.recv_from(&mut buf).await {
                // Don't reply — just forward the source addr.
                let _ = src_tx.send(from);
            }
        });

        let spoofer_sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let spoofer_port = spoofer_sock.local_addr().unwrap().port();
        assert_ne!(
            spoofer_port, gateway_port,
            "spoofer must use a different port"
        );
        let spoofer_handle = tokio::spawn(async move {
            // Forge a success reply with an attacker-chosen IP.
            // If this lands, the mapper would cache this as its
            // external — that's the poisoning vector.
            let forged = encode_external_success(Ipv4Addr::new(203, 0, 113, 66));
            while let Some(client_src) = src_rx.recv().await {
                // Blast the forged packet at the client. If the
                // `connect` filter is working, this is dropped
                // by the kernel before reaching `recv`.
                let _ = spoofer_sock.send_to(&forged, client_src).await;
            }
        });

        // The real `NatPmpMapper`, targeting the silent gateway's
        // port. With the fix in place, its UDP socket is
        // `connect()`ed to `(127.0.0.1, gateway_port)` so
        // packets from the spoofer's port are filtered out.
        let mapper = NatPmpMapper::new_for_test(Ipv4Addr::LOCALHOST, gateway_port);

        let start = tokio::time::Instant::now();
        let res = mapper.probe().await;
        let elapsed = start.elapsed();

        assert!(
            matches!(res, Err(PortMappingError::Timeout)),
            "probe must time out — spoofed response should not leak through kernel filter; \
             got {res:?} after {elapsed:?}",
        );
        assert!(
            elapsed >= Duration::from_millis(800),
            "timeout fired too early ({elapsed:?}); spoof may have short-circuited the deadline",
        );
        assert!(
            mapper.cached_external().is_none(),
            "external-IP cache must stay empty — if a spoofed IP landed here, the mesh would \
             advertise the attacker's address as its reflex",
        );

        gateway_handle.abort();
        spoofer_handle.abort();
    }

    /// Regression test for the `remove`-on-silent-gateway path.
    /// History:
    ///   - Original: `remove` went through `round_trip`, which
    ///     waited up to [`NATPMP_DEADLINE`] (1 s) per call —
    ///     mesh teardown stalled a full second per held mapping.
    ///   - Then: switched to fire-and-forget; the test pinned
    ///     "elapsed < 200 ms".
    ///   - Now (BUG_REPORT.md #41): UDP delivery to a gateway is
    ///     not the same as gateway-side processing, and some
    ///     routers refuse `lifetime=0`. The client never knew.
    ///     `remove` now does a *short-deadline* recv (200 ms) so
    ///     a healthy gateway's ack confirms removal and a
    ///     misbehaving one doesn't stall shutdown longer than
    ///     that bounded window.
    ///
    /// The contract this test pins: against a silent gateway,
    /// `remove` must complete within the bounded
    /// `REMOVE_DEADLINE` (200 ms) plus reasonable scheduler
    /// jitter — well under the original 1 s — and must NOT
    /// hang or block mesh shutdown indefinitely.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn remove_is_fire_and_forget_and_does_not_block_on_silent_gateway() {
        // Silent gateway — binds the port (so `connect` can
        // succeed on loopback) but never reads or replies.
        let silent = UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let gateway_port = silent.local_addr().unwrap().port();

        let mapper = NatPmpMapper::new_for_test(Ipv4Addr::LOCALHOST, gateway_port);
        let mapping = PortMapping {
            external: "203.0.113.1:9001".parse().unwrap(),
            internal_port: 9001,
            ttl: Duration::from_secs(3600),
            protocol: Protocol::NatPmp,
        };

        let start = tokio::time::Instant::now();
        mapper.remove(&mapping).await;
        let elapsed = start.elapsed();

        // `remove` waits up to `REMOVE_DEADLINE` (200 ms) for the
        // gateway's ack so misconfigured routers that refuse
        // `lifetime=0` are at least logged (#41). Cap the
        // bounded wait at 500 ms total — the deadline plus
        // generous scheduler jitter — so this test still catches
        // a regression to the old 1 s `NATPMP_DEADLINE` path.
        assert!(
            elapsed < Duration::from_millis(500),
            "remove() blocked for {elapsed:?} — bounded recv regressed. \
             On a silent gateway it must complete within REMOVE_DEADLINE \
             (~200 ms) plus jitter, well under the original 1 s deadline",
        );

        drop(silent);
    }

    /// Regression test for the `.unwrap_or(self.gateway)` audit
    /// (FAILURE_PATH_HARDENING_PLAN pre-flight): `install` must
    /// refuse to produce a `PortMapping` when `cached_external`
    /// is empty, rather than silently substituting the gateway's
    /// private LAN IP as the mapping's external address.
    ///
    /// Scenario: a mock gateway cheerfully answers `MapUdp`
    /// install requests with success — but we never call
    /// `probe`, so the mapper has no cached external IP. The
    /// old code path returned `Ok(PortMapping { external: <LAN
    /// gateway IP>, .. })`, poisoning downstream capability
    /// announcements. The new behavior surfaces a `Transport`
    /// error so the caller finds the missing precondition
    /// instead of publishing an unroutable address to peers.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn install_without_prior_probe_refuses_rather_than_publishing_gateway_ip() {
        // Mock gateway that responds to MapUdp but would fail
        // any ExternalAddress probe (returns None → client
        // times out). We never send a probe in this test, so
        // the probe-response behavior doesn't matter.
        let (port, gw) = spawn_mock_gateway(|req| {
            if req.len() == MAP_REQUEST_LEN && req[0] == NATPMP_VERSION && req[1] == OP_MAP_UDP {
                let internal = u16::from_be_bytes([req[4], req[5]]);
                Some(encode_map_success(internal, internal, 3600))
            } else {
                None
            }
        })
        .await;

        let mapper = NatPmpMapper::new_for_test(Ipv4Addr::LOCALHOST, port);
        assert!(
            mapper.cached_external().is_none(),
            "freshly-constructed mapper must have an empty external-IP cache",
        );

        // Call install directly, without a preceding probe.
        // The round-trip succeeds (gateway returns MapUdp
        // success), but the mapper has no cached external IP
        // to pair with the mapped port. The new behavior must
        // refuse rather than substitute `self.gateway`
        // (which is the router's private LAN address).
        let res = mapper.install(9001, Duration::from_secs(3600)).await;

        match res {
            Err(PortMappingError::Transport(msg)) => {
                assert!(
                    msg.contains("install called before successful probe"),
                    "error detail must identify the precondition violation; got {msg:?}",
                );
            }
            Ok(mapping) => panic!(
                "install must NOT silently substitute the gateway LAN IP — \
                 got mapping with external={:?}. Pre-fix behavior would publish \
                 the gateway's private address to capability announcements",
                mapping.external,
            ),
            Err(other) => panic!("expected Transport(<precondition msg>); got {other:?}",),
        }

        // And the cache is still empty — a refused install
        // must not somehow populate the cache as a side effect.
        assert!(mapper.cached_external().is_none());
        gw.abort();
    }
}