async-snmp 0.17.0

Modern async-first SNMP client library for Rust
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
//! `SNMPv3` message format (RFC 3412).
//!
//! V3 messages have a more complex structure than v1/v2c:
//! ```text
//! SEQUENCE {
//!     INTEGER version (3)
//!     SEQUENCE msgGlobalData {
//!         INTEGER msgID
//!         INTEGER msgMaxSize
//!         OCTET STRING msgFlags (1 byte)
//!         INTEGER msgSecurityModel
//!     }
//!     OCTET STRING msgSecurityParameters (opaque, USM-encoded)
//!     msgData (ScopedPDU or encrypted OCTET STRING)
//! }
//! ```
//!
//! The msgData field is either:
//! - A plaintext `ScopedPDU` (SEQUENCE) for noAuthNoPriv/authNoPriv
//! - An encrypted OCTET STRING for authPriv (decrypts to `ScopedPDU`)

use bytes::Bytes;

use crate::ber::{Decoder, EncodeBuf};
use crate::error::internal::DecodeErrorKind;
use crate::error::{Error, Result, UNKNOWN_TARGET};
use crate::pdu::Pdu;

/// Minimum `msgMaxSize` per RFC 3412 `HeaderData` (INTEGER 484..2147483647).
const MSG_MAX_SIZE_MINIMUM: i32 = 484;

/// `SNMPv3` security model identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum SecurityModel {
    /// User-based Security Model (RFC 3414)
    Usm = 3,
}

impl SecurityModel {
    /// Create from raw value.
    #[must_use]
    pub fn from_i32(value: i32) -> Option<Self> {
        match value {
            3 => Some(Self::Usm),
            _ => None,
        }
    }

    /// Get the raw value.
    #[must_use]
    pub fn as_i32(self) -> i32 {
        self as i32
    }
}

/// `SNMPv3` security level.
///
/// The variants are ordered from least secure to most secure,
/// supporting VACM-style level comparisons (e.g., `actual >= required`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SecurityLevel {
    /// No authentication, no privacy
    NoAuthNoPriv,
    /// Authentication only
    AuthNoPriv,
    /// Authentication and privacy (encryption)
    AuthPriv,
}

impl SecurityLevel {
    /// Decode from msgFlags byte.
    #[must_use]
    pub fn from_flags(flags: u8) -> Option<Self> {
        let auth = flags & 0x01 != 0;
        let priv_ = flags & 0x02 != 0;

        match (auth, priv_) {
            (false, false) => Some(Self::NoAuthNoPriv),
            (true, false) => Some(Self::AuthNoPriv),
            (true, true) => Some(Self::AuthPriv),
            (false, true) => None, // Invalid: priv without auth
        }
    }

    /// Encode to msgFlags byte (without reportable flag).
    #[must_use]
    pub fn to_flags(self) -> u8 {
        match self {
            Self::NoAuthNoPriv => 0x00,
            Self::AuthNoPriv => 0x01,
            Self::AuthPriv => 0x03,
        }
    }

    /// Check if authentication is required.
    #[must_use]
    pub fn requires_auth(self) -> bool {
        matches!(self, Self::AuthNoPriv | Self::AuthPriv)
    }

    /// Check if privacy (encryption) is required.
    #[must_use]
    pub fn requires_priv(self) -> bool {
        matches!(self, Self::AuthPriv)
    }
}

impl TryFrom<u8> for SecurityLevel {
    type Error = u8;

    fn try_from(flags: u8) -> std::result::Result<Self, u8> {
        Self::from_flags(flags).ok_or(flags)
    }
}

impl From<SecurityLevel> for u8 {
    fn from(level: SecurityLevel) -> u8 {
        level.to_flags()
    }
}

/// Message flags (RFC 3412 Section 6.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MsgFlags {
    /// Security level
    pub security_level: SecurityLevel,
    /// Whether a report PDU may be sent on error
    pub reportable: bool,
}

impl MsgFlags {
    /// Create new message flags.
    #[must_use]
    pub fn new(security_level: SecurityLevel, reportable: bool) -> Self {
        Self {
            security_level,
            reportable,
        }
    }

    /// Decode from byte.
    pub fn from_byte(byte: u8) -> Result<Self> {
        let security_level = SecurityLevel::from_flags(byte).ok_or_else(|| {
            tracing::debug!(target: "async_snmp::v3", { byte, kind = %DecodeErrorKind::InvalidMsgFlags }, "decode error");
            Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed()
        })?;
        let reportable = byte & 0x04 != 0;
        Ok(Self {
            security_level,
            reportable,
        })
    }

    /// Encode to byte.
    #[must_use]
    pub fn to_byte(self) -> u8 {
        let mut flags = self.security_level.to_flags();
        if self.reportable {
            flags |= 0x04;
        }
        flags
    }
}

/// Message global data header (msgGlobalData).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MsgGlobalData {
    /// Message identifier for request/response correlation
    pub msg_id: i32,
    /// Maximum message size the sender can accept
    pub msg_max_size: i32,
    /// Message flags (security level + reportable)
    pub msg_flags: MsgFlags,
    /// Security model (always USM=3 for our implementation)
    pub msg_security_model: SecurityModel,
}

impl MsgGlobalData {
    /// Create new global data.
    #[must_use]
    pub fn new(msg_id: i32, msg_max_size: i32, msg_flags: MsgFlags) -> Self {
        Self {
            msg_id,
            msg_max_size,
            msg_flags,
            msg_security_model: SecurityModel::Usm,
        }
    }

    /// Encode to buffer.
    pub fn encode(&self, buf: &mut EncodeBuf) {
        buf.push_sequence(|buf| {
            buf.push_integer(self.msg_security_model.as_i32());
            // msgFlags is a 1-byte OCTET STRING
            buf.push_octet_string(&[self.msg_flags.to_byte()]);
            buf.push_integer(self.msg_max_size);
            buf.push_integer(self.msg_id);
        });
    }

    /// Decode from decoder.
    ///
    /// Validates that:
    /// - `msgID` is in range 0..2147483647 (RFC 3412 `HeaderData`)
    /// - `msgMaxSize` is in range 484..2147483647 (RFC 3412 `HeaderData`)
    /// - `msgSecurityModel` is a known value (currently only USM=3)
    pub fn decode(decoder: &mut Decoder) -> Result<Self> {
        let mut seq = decoder.read_sequence()?;

        // These ASN.1 constraints must be checked against the complete BER
        // value before it is narrowed to i32.
        let msg_id = seq.read_bounded_integer(0, i32::MAX)?;
        let msg_max_size = seq.read_bounded_integer(MSG_MAX_SIZE_MINIMUM, i32::MAX)?;

        let flags_bytes = seq.read_octet_string()?;
        if flags_bytes.len() != 1 {
            tracing::debug!(target: "async_snmp::v3", { offset = seq.offset(), expected = 1, actual = flags_bytes.len() }, "invalid msgFlags length");
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }
        let msg_flags = MsgFlags::from_byte(flags_bytes[0])?;

        let msg_security_model_raw = seq.read_bounded_integer(1, i32::MAX)?;
        // Reject unknown security models per RFC 3412 Section 7.2
        let msg_security_model =
            SecurityModel::from_i32(msg_security_model_raw).ok_or_else(|| {
                tracing::debug!(target: "async_snmp::v3", { offset = seq.offset(), model = msg_security_model_raw, kind = %DecodeErrorKind::UnknownSecurityModel(msg_security_model_raw) }, "decode error");
                Error::MalformedResponse {
                    target: UNKNOWN_TARGET,
                }
                .boxed()
            })?;

        if !seq.is_empty() {
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        Ok(Self {
            msg_id,
            msg_max_size,
            msg_flags,
            msg_security_model,
        })
    }
}

/// Scoped PDU (contextEngineID + contextName + PDU).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopedPdu {
    /// Context engine ID (typically same as authoritative engine ID)
    pub context_engine_id: Bytes,
    /// Context name (typically empty string)
    pub context_name: Bytes,
    /// The actual PDU
    pub pdu: Pdu,
}

impl ScopedPdu {
    /// Create a new scoped PDU.
    pub fn new(
        context_engine_id: impl Into<Bytes>,
        context_name: impl Into<Bytes>,
        pdu: Pdu,
    ) -> Self {
        Self {
            context_engine_id: context_engine_id.into(),
            context_name: context_name.into(),
            pdu,
        }
    }

    /// Create with empty context (most common case).
    #[must_use]
    pub fn with_empty_context(pdu: Pdu) -> Self {
        Self {
            context_engine_id: Bytes::new(),
            context_name: Bytes::new(),
            pdu,
        }
    }

    /// Encode to buffer.
    pub fn encode(&self, buf: &mut EncodeBuf) {
        buf.push_sequence(|buf| {
            self.pdu.encode(buf);
            buf.push_octet_string(&self.context_name);
            buf.push_octet_string(&self.context_engine_id);
        });
    }

    /// Encode to bytes.
    pub fn encode_to_bytes(&self) -> Bytes {
        let mut buf = EncodeBuf::new();
        self.encode(&mut buf);
        buf.finish()
    }

    /// Decode from decoder.
    pub fn decode(decoder: &mut Decoder) -> Result<Self> {
        let mut seq = decoder.read_sequence()?;

        let context_engine_id = seq.read_octet_string()?;
        let context_name = seq.read_octet_string()?;
        let pdu = Pdu::decode(&mut seq)?;

        if !seq.is_empty() {
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        Ok(Self {
            context_engine_id,
            context_name,
            pdu,
        })
    }
}

/// `SNMPv3` message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct V3Message {
    /// Global data (header)
    pub global_data: MsgGlobalData,
    /// Security parameters (opaque, USM-encoded)
    pub security_params: Bytes,
    /// Message data - either plaintext `ScopedPdu` or encrypted bytes
    pub data: V3MessageData,
}

/// Message data payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum V3MessageData {
    /// Plaintext scoped PDU (noAuthNoPriv or authNoPriv)
    Plaintext(ScopedPdu),
    /// Encrypted scoped PDU (authPriv) - raw ciphertext
    Encrypted(Bytes),
}

impl V3Message {
    /// Create a new V3 message with plaintext data.
    pub fn new(global_data: MsgGlobalData, security_params: Bytes, scoped_pdu: ScopedPdu) -> Self {
        Self {
            global_data,
            security_params,
            data: V3MessageData::Plaintext(scoped_pdu),
        }
    }

    /// Create a new V3 message with encrypted data.
    pub fn new_encrypted(
        global_data: MsgGlobalData,
        security_params: Bytes,
        encrypted: Bytes,
    ) -> Self {
        Self {
            global_data,
            security_params,
            data: V3MessageData::Encrypted(encrypted),
        }
    }

    /// Get the scoped PDU if available (plaintext only).
    pub fn scoped_pdu(&self) -> Option<&ScopedPdu> {
        match &self.data {
            V3MessageData::Plaintext(pdu) => Some(pdu),
            V3MessageData::Encrypted(_) => None,
        }
    }

    /// Consume and return the scoped PDU if available.
    pub fn into_scoped_pdu(self) -> Option<ScopedPdu> {
        match self.data {
            V3MessageData::Plaintext(pdu) => Some(pdu),
            V3MessageData::Encrypted(_) => None,
        }
    }

    /// Get the PDU if available (convenience method).
    pub fn pdu(&self) -> Option<&Pdu> {
        self.scoped_pdu().map(|s| &s.pdu)
    }

    /// Consume and return the PDU.
    pub fn into_pdu(self) -> Option<Pdu> {
        self.into_scoped_pdu().map(|s| s.pdu)
    }

    /// Get the message ID.
    pub fn msg_id(&self) -> i32 {
        self.global_data.msg_id
    }

    /// Get the security level.
    pub fn security_level(&self) -> SecurityLevel {
        self.global_data.msg_flags.security_level
    }

    /// Encode to BER.
    ///
    /// Note: For authenticated messages, the caller must:
    /// 1. Encode with placeholder auth params (12 zero bytes for HMAC-96)
    /// 2. Compute HMAC over the entire encoded message
    /// 3. Replace the placeholder with the actual HMAC
    pub fn encode(&self) -> Bytes {
        let mut buf = EncodeBuf::new();

        buf.push_sequence(|buf| {
            // msgData
            match &self.data {
                V3MessageData::Plaintext(scoped_pdu) => {
                    scoped_pdu.encode(buf);
                }
                V3MessageData::Encrypted(ciphertext) => {
                    buf.push_octet_string(ciphertext);
                }
            }

            // msgSecurityParameters (as OCTET STRING)
            buf.push_octet_string(&self.security_params);

            // msgGlobalData
            self.global_data.encode(buf);

            // version
            buf.push_integer(3);
        });

        buf.finish()
    }

    /// Decode from BER.
    ///
    /// For encrypted messages, returns `V3MessageData::Encrypted` with the raw
    /// ciphertext. For plaintext messages this parses the scoped PDU without
    /// performing USM authentication. Receive paths handling untrusted input
    /// should use [`RawV3Message::decode`] so authentication and timeliness can
    /// precede scoped-PDU parsing.
    pub fn decode(data: Bytes) -> Result<Self> {
        let mut decoder = Decoder::new(data);
        let mut seq = decoder.read_sequence()?;

        // Version
        let version = seq.read_bounded_integer(0, i32::MAX)?;
        if version != 3 {
            tracing::debug!(target: "async_snmp::v3", { offset = seq.offset(), version, kind = %DecodeErrorKind::UnknownVersion(version) }, "decode error");
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        Self::decode_from_sequence(&mut seq)
    }

    /// Decode from a sequence decoder where version has already been read.
    pub(crate) fn decode_from_sequence(seq: &mut Decoder) -> Result<Self> {
        // msgGlobalData
        let global_data = MsgGlobalData::decode(seq)?;

        // msgSecurityParameters (OCTET STRING containing USM params)
        let security_params = seq.read_octet_string()?;

        // msgData - either plaintext SEQUENCE or encrypted OCTET STRING
        let data = if global_data.msg_flags.security_level.requires_priv() {
            // Encrypted: expect OCTET STRING
            let encrypted = seq.read_octet_string()?;
            V3MessageData::Encrypted(encrypted)
        } else {
            // Plaintext: expect SEQUENCE (ScopedPDU)
            let scoped_pdu = ScopedPdu::decode(seq)?;
            V3MessageData::Plaintext(scoped_pdu)
        };

        Ok(Self {
            global_data,
            security_params,
            data,
        })
    }

    /// Create a discovery request message.
    ///
    /// This is sent to discover a remote SNMP engine's identity and message-size
    /// limit. The response is unauthenticated, so its boots/time tuple must not
    /// establish trusted time; authenticated communication performs that step.
    /// Uses empty security parameters and no authentication.
    #[must_use]
    pub fn discovery_request(msg_id: i32) -> Self {
        let global_data = MsgGlobalData::new(
            msg_id,
            65507, // max UDP size
            MsgFlags::new(SecurityLevel::NoAuthNoPriv, true),
        );

        // Empty USM security parameters for discovery
        let security_params = crate::v3::UsmSecurityParams::empty().encode();

        // Empty scoped PDU with Report request
        let pdu = Pdu::get_request(0, &[]);
        let scoped_pdu = ScopedPdu::with_empty_context(pdu);

        Self::new(global_data, security_params, scoped_pdu)
    }
}

/// An `SNMPv3` message whose msgData has not been through security
/// processing.
///
/// [`RawV3Message::decode`] parses only the outer envelope: version, global
/// header, and the opaque security parameters. The scoped PDU stays as raw
/// bytes (plaintext or ciphertext) so that authentication and decryption can
/// run before any PDU parsing, in the RFC 3412 Section 7.2 order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawV3Message {
    /// Global data (header)
    pub(crate) global_data: MsgGlobalData,
    /// Security parameters (opaque, USM-encoded)
    pub(crate) security_params: Bytes,
    /// Raw msgData, form selected by the received privacy flag
    pub(crate) msg_data: RawMsgData,
}

/// Raw msgData payload of a [`RawV3Message`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RawMsgData {
    /// Unparsed plaintext `ScopedPDU` TLV bytes (noAuthNoPriv or authNoPriv)
    Plaintext(Bytes),
    /// Encrypted `ScopedPDU` ciphertext (authPriv)
    Encrypted(Bytes),
}

impl RawV3Message {
    /// Decode the outer envelope from BER without touching the scoped PDU.
    ///
    /// The received security level is derived from the message's own flags;
    /// invalid flag combinations (privacy without authentication) are
    /// rejected here, before any authentication or PDU processing.
    pub fn decode(data: Bytes) -> Result<Self> {
        let mut decoder = Decoder::new(data);
        let mut seq = decoder.read_sequence()?;

        let version = seq.read_bounded_integer(0, i32::MAX)?;
        if version != 3 {
            tracing::debug!(target: "async_snmp::v3", { offset = seq.offset(), version, kind = %DecodeErrorKind::UnknownVersion(version) }, "decode error");
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        let global_data = MsgGlobalData::decode(&mut seq)?;
        let security_params = seq.read_octet_string()?;

        let msg_data = if global_data.msg_flags.security_level.requires_priv() {
            RawMsgData::Encrypted(seq.read_octet_string()?)
        } else {
            // Capture the complete plaintext ScopedPDU TLV unparsed.
            let start = seq.offset();
            seq.skip_tlv()?;
            RawMsgData::Plaintext(seq.as_bytes().slice(start..seq.offset()))
        };

        if !seq.is_empty() || !decoder.is_empty() {
            return Err(Error::MalformedResponse {
                target: UNKNOWN_TARGET,
            }
            .boxed());
        }

        Ok(Self {
            global_data,
            security_params,
            msg_data,
        })
    }

    /// Get the decoded global header.
    pub fn global_data(&self) -> &MsgGlobalData {
        &self.global_data
    }

    /// Get the opaque security parameters.
    pub fn security_params(&self) -> &Bytes {
        &self.security_params
    }

    /// Get the unprocessed message data.
    pub fn msg_data(&self) -> &RawMsgData {
        &self.msg_data
    }

    /// Get the message ID.
    pub fn msg_id(&self) -> i32 {
        self.global_data.msg_id
    }

    /// Get the security level indicated by the received flags.
    pub fn security_level(&self) -> SecurityLevel {
        self.global_data.msg_flags.security_level
    }
}

/// RFC 3412 MPD failures that must be counted before the message is
/// discarded (Sections 7.2.4 and 7.2.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MpdFailure {
    /// Invalid msgFlags (priv without auth) - snmpInvalidMsgs.
    InvalidMsgFlags,
    /// Unrecognized msgSecurityModel - snmpUnknownSecurityModels.
    UnknownSecurityModel,
}

/// Classify a failed [`V3Message::decode`] as an MPD-countable failure.
///
/// Re-parses only the header path so it stays in lockstep with
/// [`MsgGlobalData::decode`]: the first countable defect wins, and `None`
/// means the failure was some other malformation.
pub(crate) fn classify_mpd_failure(data: Bytes) -> Option<MpdFailure> {
    let mut decoder = Decoder::new(data);
    let mut seq = decoder.read_sequence().ok()?;
    if seq.read_bounded_integer(0, i32::MAX).ok()? != 3 {
        return None;
    }
    let mut global = seq.read_sequence().ok()?;
    // Mirror `MsgGlobalData::decode`'s fail-fast order so a failure is only
    // attributed to the field that actually caused decode to reject. A
    // countable defect at a later field is unreachable once decode would have
    // stopped at an earlier one (out-of-range msgID/msgMaxSize, wrong-length
    // msgFlags), and those earlier rejections are ASN.1/header errors rather
    // than snmpInvalidMsgs/snmpUnknownSecurityModels, so they return None.
    global.read_bounded_integer(0, i32::MAX).ok()?;
    global
        .read_bounded_integer(MSG_MAX_SIZE_MINIMUM, i32::MAX)
        .ok()?;
    let flags_bytes = global.read_octet_string().ok()?;
    if flags_bytes.len() != 1 {
        return None;
    }
    if MsgFlags::from_byte(flags_bytes[0]).is_err() {
        return Some(MpdFailure::InvalidMsgFlags);
    }
    let model = global.read_bounded_integer(1, i32::MAX).ok()?;
    if SecurityModel::from_i32(model).is_none() {
        return Some(MpdFailure::UnknownSecurityModel);
    }
    None
}

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

    fn push_integer_content(buf: &mut EncodeBuf, content: &[u8]) {
        buf.push_bytes(content);
        buf.push_length(content.len());
        buf.push_tag(crate::ber::tag::universal::INTEGER);
    }

    fn global_data_with_integer_contents(
        msg_id: &[u8],
        msg_max_size: &[u8],
        security_model: &[u8],
    ) -> Bytes {
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            push_integer_content(buf, security_model);
            buf.push_octet_string(&[0x04]);
            push_integer_content(buf, msg_max_size);
            push_integer_content(buf, msg_id);
        });
        buf.finish()
    }

    #[test]
    fn test_security_level_flags() {
        assert_eq!(SecurityLevel::NoAuthNoPriv.to_flags(), 0x00);
        assert_eq!(SecurityLevel::AuthNoPriv.to_flags(), 0x01);
        assert_eq!(SecurityLevel::AuthPriv.to_flags(), 0x03);

        assert_eq!(
            SecurityLevel::from_flags(0x00),
            Some(SecurityLevel::NoAuthNoPriv)
        );
        assert_eq!(
            SecurityLevel::from_flags(0x01),
            Some(SecurityLevel::AuthNoPriv)
        );
        assert_eq!(
            SecurityLevel::from_flags(0x03),
            Some(SecurityLevel::AuthPriv)
        );
        assert_eq!(SecurityLevel::from_flags(0x02), None); // Invalid
    }

    #[test]
    fn security_level_try_from_u8() {
        assert_eq!(
            SecurityLevel::try_from(0x00),
            Ok(SecurityLevel::NoAuthNoPriv)
        );
        assert_eq!(SecurityLevel::try_from(0x01), Ok(SecurityLevel::AuthNoPriv));
        assert_eq!(SecurityLevel::try_from(0x03), Ok(SecurityLevel::AuthPriv));
        assert_eq!(SecurityLevel::try_from(0x02), Err(0x02));
    }

    #[test]
    fn security_level_into_u8() {
        assert_eq!(u8::from(SecurityLevel::NoAuthNoPriv), 0x00);
        assert_eq!(u8::from(SecurityLevel::AuthNoPriv), 0x01);
        assert_eq!(u8::from(SecurityLevel::AuthPriv), 0x03);
    }

    #[test]
    fn test_msg_flags_roundtrip() {
        let flags = MsgFlags::new(SecurityLevel::AuthPriv, true);
        let byte = flags.to_byte();
        assert_eq!(byte, 0x07); // auth=1, priv=1, reportable=1

        let decoded = MsgFlags::from_byte(byte).unwrap();
        assert_eq!(decoded.security_level, SecurityLevel::AuthPriv);
        assert!(decoded.reportable);
    }

    /// `classify_mpd_failure` must attribute a failure only to the field that
    /// actually caused `MsgGlobalData::decode` to reject, matching its
    /// fail-fast order: a message rejected at an earlier field (here a
    /// negative msgID) must not be blamed on a later unknown security model.
    #[test]
    fn classify_mpd_failure_mirrors_decode_fail_fast() {
        use crate::pdu::Pdu;
        use crate::v3::UsmSecurityParams;

        // Valid noAuthNoPriv v3 message; single-byte msgID and model keep the
        // byte patches below length-preserving.
        let global = MsgGlobalData::new(1, 65507, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));
        let usm =
            UsmSecurityParams::new(Bytes::from_static(b"eid"), 0, 0, Bytes::from_static(b"u"));
        let scoped = ScopedPdu::new(
            Bytes::from_static(b"eid"),
            Bytes::new(),
            Pdu::get_request(42, &[]),
        );
        let base = V3Message::new(global, usm.encode(), scoped).encode();

        let patch = |data: &Bytes, pattern: &[u8], off: usize, val: u8| -> Bytes {
            let mut b = data.to_vec();
            let pos = b
                .windows(pattern.len())
                .position(|w| w == pattern)
                .expect("pattern not found");
            b[pos + off] = val;
            Bytes::from(b)
        };

        // Only the security model is unknown -> UnknownSecurityModel.
        let model_pattern = [0x04, 0x01, 0x04, 0x02, 0x01, 0x03];
        let unknown_model = patch(&base, &model_pattern, 5, 99);
        assert_eq!(
            classify_mpd_failure(unknown_model),
            Some(MpdFailure::UnknownSecurityModel)
        );

        // Decode rejects at the negative msgID before reaching the model, so
        // the unknown model must not be attributed.
        let neg_id = patch(&base, &[0x02, 0x01, 0x01, 0x02, 0x03], 2, 0x81);
        let neg_id_unknown_model = patch(&neg_id, &model_pattern, 5, 99);
        assert_eq!(classify_mpd_failure(neg_id_unknown_model), None);
    }

    /// A valid envelope around a malformed plaintext scoped PDU must decode
    /// as a raw message (the scoped PDU is not parsed), while the eager
    /// decode fails. This is the invariant that lets HMAC verification run
    /// before plaintext PDU parsing.
    #[test]
    fn raw_decode_does_not_parse_plaintext_scoped_pdu() {
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            // msgData: structurally a SEQUENCE TLV, but garbage inside
            buf.push_sequence(|buf| {
                buf.push_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]);
            });
            buf.push_octet_string(b"usm-params");
            MsgGlobalData::new(7, 65507, MsgFlags::new(SecurityLevel::AuthNoPriv, false))
                .encode(buf);
            buf.push_integer(3);
        });
        let encoded = buf.finish();

        assert!(
            V3Message::decode(encoded.clone()).is_err(),
            "eager decode must reject the malformed scoped PDU"
        );

        let raw = RawV3Message::decode(encoded).unwrap();
        assert_eq!(raw.msg_id(), 7);
        assert_eq!(raw.security_level(), SecurityLevel::AuthNoPriv);
        assert_eq!(raw.security_params.as_ref(), b"usm-params");
        let RawMsgData::Plaintext(scoped) = raw.msg_data else {
            panic!("expected plaintext msgData");
        };
        assert_eq!(scoped.as_ref(), &[0x30, 0x04, 0xDE, 0xAD, 0xBE, 0xEF]);
    }

    #[test]
    fn v3_decoders_reject_over_width_version_alias() {
        let global = MsgGlobalData::new(7, 1472, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));
        let scoped = ScopedPdu::with_empty_context(Pdu::get_request(42, &[]));
        let security_params = crate::v3::UsmSecurityParams::empty().encode();

        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            scoped.encode(buf);
            buf.push_octet_string(&security_params);
            global.encode(buf);
            // 2^32 + 3 previously narrowed to the accepted v3 value.
            push_integer_content(buf, &[0x01, 0x00, 0x00, 0x00, 0x03]);
        });
        let encoded = buf.finish();

        assert!(V3Message::decode(encoded.clone()).is_err());
        assert!(RawV3Message::decode(encoded.clone()).is_err());
        assert!(crate::message::Message::decode(encoded).is_err());
    }

    /// The captured plaintext bytes are the complete ScopedPDU TLV, so a
    /// later parse of a well-formed message succeeds from the raw bytes.
    #[test]
    fn raw_plaintext_bytes_reparse_as_scoped_pdu() {
        let global = MsgGlobalData::new(9, 1472, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));
        let pdu = Pdu::get_request(42, &[oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)]);
        let scoped = ScopedPdu::new(b"eng".as_slice(), b"ctx".as_slice(), pdu);
        let msg = V3Message::new(global, Bytes::from_static(b"usm"), scoped);

        let raw = RawV3Message::decode(msg.encode()).unwrap();
        let RawMsgData::Plaintext(bytes) = raw.msg_data else {
            panic!("expected plaintext msgData");
        };
        let mut decoder = Decoder::new(bytes);
        let reparsed = ScopedPdu::decode(&mut decoder).unwrap();
        assert_eq!(reparsed.context_engine_id.as_ref(), b"eng");
        assert_eq!(reparsed.context_name.as_ref(), b"ctx");
        assert_eq!(reparsed.pdu.request_id, 42);
    }

    /// authPriv messages keep their ciphertext untouched.
    #[test]
    fn raw_decode_keeps_ciphertext() {
        let global = MsgGlobalData::new(200, 1472, MsgFlags::new(SecurityLevel::AuthPriv, false));
        let msg = V3Message::new_encrypted(
            global,
            Bytes::from_static(b"usm-params"),
            Bytes::from_static(b"encrypted-data"),
        );

        let raw = RawV3Message::decode(msg.encode()).unwrap();
        assert_eq!(raw.security_level(), SecurityLevel::AuthPriv);
        let RawMsgData::Encrypted(ciphertext) = raw.msg_data else {
            panic!("expected encrypted msgData");
        };
        assert_eq!(ciphertext.as_ref(), b"encrypted-data");
    }

    /// Privacy without authentication is rejected during envelope decode,
    /// before any authentication or PDU work can start.
    #[test]
    fn raw_decode_rejects_priv_without_auth_flags() {
        let global = MsgGlobalData::new(1, 65507, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));
        let pdu = Pdu::get_request(1, &[]);
        let msg = V3Message::new(
            global,
            Bytes::from_static(b"usm"),
            ScopedPdu::with_empty_context(pdu),
        );
        let mut bytes = msg.encode().to_vec();
        // Locate the single-byte msgFlags OCTET STRING (0x04 0x01 0x04) and
        // patch it to priv-without-auth (0x02).
        let pos = bytes
            .windows(3)
            .position(|w| w == [0x04, 0x01, 0x04])
            .expect("msgFlags not found");
        bytes[pos + 2] = 0x02;

        let result = RawV3Message::decode(Bytes::from(bytes));
        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    /// Reserved and reportable flag bits do not alter the derived security
    /// level (RFC 3412 Section 7.2 derives the level from the auth/priv bits
    /// only).
    #[test]
    fn raw_decode_ignores_reserved_bits_for_level() {
        let global = MsgGlobalData::new(1, 65507, MsgFlags::new(SecurityLevel::AuthNoPriv, false));
        let pdu = Pdu::get_request(1, &[]);
        let msg = V3Message::new(
            global,
            Bytes::from_static(b"usm"),
            ScopedPdu::with_empty_context(pdu),
        );
        let mut bytes = msg.encode().to_vec();
        let pos = bytes
            .windows(3)
            .position(|w| w == [0x04, 0x01, 0x01])
            .expect("msgFlags not found");
        // auth + reportable + a reserved bit
        bytes[pos + 2] = 0x01 | 0x04 | 0x08;

        let raw = RawV3Message::decode(Bytes::from(bytes)).unwrap();
        assert_eq!(raw.security_level(), SecurityLevel::AuthNoPriv);
        assert!(raw.global_data.msg_flags.reportable);
    }

    #[test]
    fn raw_decode_rejects_trailing_envelope_fields() {
        let global =
            MsgGlobalData::new(17, 1472, MsgFlags::new(SecurityLevel::NoAuthNoPriv, false));
        let scoped = ScopedPdu::with_empty_context(Pdu::get_request(23, &[]));

        // Encode an extra INTEGER after msgData inside the outer sequence.
        let mut with_outer_field = EncodeBuf::new();
        with_outer_field.push_sequence(|buf| {
            buf.push_integer(99);
            scoped.encode(buf);
            buf.push_octet_string(b"usm");
            global.encode(buf);
            buf.push_integer(3);
        });
        assert!(RawV3Message::decode(with_outer_field.finish()).is_err());

        // Encode an extra INTEGER inside msgGlobalData.
        let mut with_global_field = EncodeBuf::new();
        with_global_field.push_sequence(|buf| {
            scoped.encode(buf);
            buf.push_octet_string(b"usm");
            buf.push_sequence(|buf| {
                buf.push_integer(99);
                buf.push_integer(SecurityModel::Usm.as_i32());
                buf.push_octet_string(&[0]);
                buf.push_integer(1472);
                buf.push_integer(17);
            });
            buf.push_integer(3);
        });
        assert!(RawV3Message::decode(with_global_field.finish()).is_err());

        // Append another top-level TLV after an otherwise complete message.
        let message = V3Message::new(global, Bytes::from_static(b"usm"), scoped);
        let mut with_root_trailing = message.encode().to_vec();
        with_root_trailing.extend_from_slice(&[0x05, 0]);
        assert!(RawV3Message::decode(Bytes::from(with_root_trailing)).is_err());
    }

    #[test]
    fn test_msg_global_data_roundtrip() {
        let global =
            MsgGlobalData::new(12345, 1472, MsgFlags::new(SecurityLevel::AuthNoPriv, true));

        let mut buf = EncodeBuf::new();
        global.encode(&mut buf);
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_id, 12345);
        assert_eq!(decoded.msg_max_size, 1472);
        assert_eq!(decoded.msg_flags.security_level, SecurityLevel::AuthNoPriv);
        assert!(decoded.msg_flags.reportable);
        assert_eq!(decoded.msg_security_model, SecurityModel::Usm);
    }

    #[test]
    fn test_scoped_pdu_roundtrip() {
        let pdu = Pdu::get_request(42, &[oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)]);
        let scoped = ScopedPdu::new(b"engine".as_slice(), b"ctx".as_slice(), pdu);

        let mut buf = EncodeBuf::new();
        scoped.encode(&mut buf);
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = ScopedPdu::decode(&mut decoder).unwrap();

        assert_eq!(decoded.context_engine_id.as_ref(), b"engine");
        assert_eq!(decoded.context_name.as_ref(), b"ctx");
        assert_eq!(decoded.pdu.request_id, 42);
    }

    #[test]
    fn scoped_pdu_rejects_trailing_sequence_fields() {
        let pdu = Pdu::get_request(42, &[]);
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(99);
            pdu.encode(buf);
            buf.push_octet_string(b"ctx");
            buf.push_octet_string(b"engine");
        });

        let mut decoder = Decoder::new(buf.finish());
        assert!(ScopedPdu::decode(&mut decoder).is_err());
    }

    #[test]
    fn test_v3_message_plaintext_roundtrip() {
        let global =
            MsgGlobalData::new(100, 1472, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));
        let pdu = Pdu::get_request(42, &[oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)]);
        let scoped = ScopedPdu::with_empty_context(pdu);
        let msg = V3Message::new(global, Bytes::from_static(b"usm-params"), scoped);

        let encoded = msg.encode();
        let decoded = V3Message::decode(encoded).unwrap();

        assert_eq!(decoded.global_data.msg_id, 100);
        assert_eq!(decoded.security_level(), SecurityLevel::NoAuthNoPriv);
        assert_eq!(decoded.security_params.as_ref(), b"usm-params");

        let scoped_pdu = decoded.scoped_pdu().unwrap();
        assert_eq!(scoped_pdu.pdu.request_id, 42);
    }

    #[test]
    fn test_v3_message_encrypted_roundtrip() {
        let global = MsgGlobalData::new(200, 1472, MsgFlags::new(SecurityLevel::AuthPriv, false));
        let msg = V3Message::new_encrypted(
            global,
            Bytes::from_static(b"usm-params"),
            Bytes::from_static(b"encrypted-data"),
        );

        let encoded = msg.encode();
        let decoded = V3Message::decode(encoded).unwrap();

        assert_eq!(decoded.global_data.msg_id, 200);
        assert_eq!(decoded.security_level(), SecurityLevel::AuthPriv);

        match &decoded.data {
            V3MessageData::Encrypted(data) => {
                assert_eq!(data.as_ref(), b"encrypted-data");
            }
            V3MessageData::Plaintext(_) => panic!("expected encrypted data"),
        }
    }

    #[test]
    fn test_msg_global_data_rejects_msg_max_size_below_minimum() {
        // Encode with invalid msgMaxSize (below 484)
        let global = MsgGlobalData {
            msg_id: 100,
            msg_max_size: 400, // Below RFC 3412 minimum of 484
            msg_flags: MsgFlags::new(SecurityLevel::NoAuthNoPriv, true),
            msg_security_model: SecurityModel::Usm,
        };

        let mut buf = EncodeBuf::new();
        global.encode(&mut buf);
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn test_msg_global_data_accepts_msg_max_size_at_minimum() {
        // 484 is exactly the RFC 3412 minimum
        let global = MsgGlobalData::new(100, 484, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));

        let mut buf = EncodeBuf::new();
        global.encode(&mut buf);
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_max_size, 484);
    }

    #[test]
    fn test_msg_global_data_rejects_unknown_security_model() {
        // Manually build encoded data with unknown security model
        // SEQUENCE { msg_id, msg_max_size, msgFlags, msgSecurityModel=99 }
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(99); // unknown security model
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(1472); // msg_max_size
            buf.push_integer(100); // msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn msg_global_data_rejects_over_width_integer_aliases() {
        const ZERO: &[u8] = &[0x00];
        const MSG_MAX_SIZE: &[u8] = &[0x05, 0xC0];
        const USM: &[u8] = &[0x03];

        // Each value is 2^32 plus an otherwise accepted field value.
        let aliased_msg_id =
            global_data_with_integer_contents(&[0x01, 0x00, 0x00, 0x00, 0x00], MSG_MAX_SIZE, USM);
        let aliased_msg_max_size =
            global_data_with_integer_contents(ZERO, &[0x01, 0x00, 0x00, 0x05, 0xC0], USM);
        let aliased_security_model =
            global_data_with_integer_contents(ZERO, MSG_MAX_SIZE, &[0x01, 0x00, 0x00, 0x00, 0x03]);

        for encoded in [aliased_msg_id, aliased_msg_max_size, aliased_security_model] {
            let mut decoder = Decoder::new(encoded);
            assert!(MsgGlobalData::decode(&mut decoder).is_err());
        }
    }

    #[test]
    fn test_msg_global_data_rejects_zero_length_msg_flags() {
        // RFC 3412 Section 6.4: msgFlags OCTET STRING (SIZE(1))
        // SEQUENCE { msg_id, msg_max_size, msgFlags=<empty>, msgSecurityModel=3(Usm) }
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // Usm
            buf.push_octet_string(&[]); // zero-length msgFlags
            buf.push_integer(1472); // msg_max_size
            buf.push_integer(100); // msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn test_msg_global_data_rejects_two_byte_msg_flags() {
        // RFC 3412 Section 6.4: msgFlags OCTET STRING (SIZE(1))
        // SEQUENCE { msg_id, msg_max_size, msgFlags=<two bytes>, msgSecurityModel=3(Usm) }
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // Usm
            buf.push_octet_string(&[0x04, 0x00]); // two-byte msgFlags
            buf.push_integer(1472); // msg_max_size
            buf.push_integer(100); // msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn test_msg_global_data_accepts_one_byte_msg_flags() {
        // Control: a valid single-byte msgFlags (reportable, noAuthNoPriv) must be accepted
        // SEQUENCE { msg_id, msg_max_size, msgFlags=[0x04], msgSecurityModel=3(Usm) }
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // Usm
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(1472); // msg_max_size
            buf.push_integer(100); // msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_flags, MsgFlags::from_byte(0x04).unwrap());
        assert_eq!(decoded.msg_security_model, SecurityModel::Usm);
    }

    #[test]
    fn test_msg_global_data_accepts_usm_security_model() {
        // USM (3) should be accepted
        let global =
            MsgGlobalData::new(100, 1472, MsgFlags::new(SecurityLevel::NoAuthNoPriv, true));

        let mut buf = EncodeBuf::new();
        global.encode(&mut buf);
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_security_model, SecurityModel::Usm);
    }

    // RFC 3412 bounds tests for msgID and msgMaxSize
    //
    // RFC 3412 HeaderData definition specifies:
    //   msgID INTEGER (0..2147483647)
    //   msgMaxSize INTEGER (484..2147483647)
    //
    // Values outside these ranges should be rejected.

    #[test]
    fn test_msg_global_data_rejects_negative_msg_id() {
        // RFC 3412: msgID must be in range [0..2147483647]
        // Negative values should be rejected
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // USM security model
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(1472); // valid msg_max_size
            buf.push_integer(-1); // negative msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn test_msg_global_data_rejects_negative_msg_max_size() {
        // RFC 3412: msgMaxSize must be in range [484..2147483647]
        // Negative values (from signed integer interpretation) should be rejected
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // USM security model
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(-1); // negative msg_max_size (would be > 2^31-1 unsigned)
            buf.push_integer(100); // valid msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let result = MsgGlobalData::decode(&mut decoder);

        assert!(result.is_err());
        assert!(matches!(
            *result.unwrap_err(),
            Error::MalformedResponse { .. }
        ));
    }

    #[test]
    fn test_msg_global_data_accepts_msg_id_at_zero() {
        // RFC 3412: msgID 0 is at the lower bound, should be accepted
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // USM
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(1472); // valid msg_max_size
            buf.push_integer(0); // msg_id at lower bound
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_id, 0);
    }

    #[test]
    fn test_msg_global_data_accepts_msg_id_at_maximum() {
        // RFC 3412: msgID 2147483647 is at the upper bound, should be accepted
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // USM
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(1472); // valid msg_max_size
            buf.push_integer(i32::MAX); // msg_id at upper bound (2147483647)
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_id, i32::MAX);
    }

    #[test]
    fn test_msg_global_data_accepts_msg_max_size_at_maximum() {
        // RFC 3412: msgMaxSize 2147483647 is at the upper bound, should be accepted
        let mut buf = EncodeBuf::new();
        buf.push_sequence(|buf| {
            buf.push_integer(3); // USM
            buf.push_octet_string(&[0x04]); // reportable, noAuthNoPriv
            buf.push_integer(i32::MAX); // msg_max_size at upper bound (2147483647)
            buf.push_integer(100); // valid msg_id
        });
        let encoded = buf.finish();

        let mut decoder = Decoder::new(encoded);
        let decoded = MsgGlobalData::decode(&mut decoder).unwrap();

        assert_eq!(decoded.msg_max_size, i32::MAX);
    }
}