async-snmp 0.12.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
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
//! View-based Access Control Model (RFC 3415).
//!
//! VACM controls access to MIB objects based on who is making the request
//! and what they are trying to access. It implements fine-grained access control
//! through a three-table architecture.
//!
//! # Overview
//!
//! VACM (View-based Access Control Model) is the standard access control mechanism
//! for SNMPv3, though it can also be used with SNMPv1/v2c. It answers the question:
//! "Can this user perform this operation on this OID?"
//!
//! # Architecture
//!
//! VACM controls access through three tables:
//!
//! 1. **Security-to-Group Table**: Maps (securityModel, securityName) to groupName.
//!    This groups users/communities with similar access rights.
//!
//! 2. **Access Table**: Maps (groupName, contextPrefix, securityModel, securityLevel)
//!    to view names for read, write, and notify operations.
//!
//! 3. **View Tree Family Table**: Defines views as collections of OID subtrees,
//!    with optional inclusion/exclusion and wildcard masks.
//!
//! # Basic Example
//!
//! Configure read-only access for "public" community:
//!
//! ```rust
//! use async_snmp::agent::{Agent, SecurityModel, VacmBuilder};
//! use async_snmp::oid;
//!
//! # fn example() {
//! let vacm = VacmBuilder::new()
//!     // Map "public" community to "readonly_group"
//!     .group("public", SecurityModel::V2c, "readonly_group")
//!     // Grant read access to full_view
//!     .access("readonly_group", |a| a.read_view("full_view"))
//!     // Define what OIDs are in full_view
//!     .view("full_view", |v| v.include(oid!(1, 3, 6, 1)))
//!     .build();
//! # }
//! ```
//!
//! # Read/Write Access Example
//!
//! Configure different access levels for different users:
//!
//! ```rust
//! use async_snmp::agent::{Agent, SecurityModel, VacmBuilder};
//! use async_snmp::message::SecurityLevel;
//! use async_snmp::oid;
//!
//! # fn example() {
//! let vacm = VacmBuilder::new()
//!     // Read-only community
//!     .group("public", SecurityModel::V2c, "readers")
//!     // Read-write community
//!     .group("private", SecurityModel::V2c, "writers")
//!     // SNMPv3 admin user
//!     .group("admin", SecurityModel::Usm, "admins")
//!
//!     // Readers can only read
//!     .access("readers", |a| a
//!         .read_view("system_view"))
//!
//!     // Writers can read everything and write to ifAdminStatus
//!     .access("writers", |a| a
//!         .read_view("full_view")
//!         .write_view("if_admin_view"))
//!
//!     // Admins require encryption and can read/write everything
//!     .access("admins", |a| a
//!         .security_model(SecurityModel::Usm)
//!         .security_level(SecurityLevel::AuthPriv)
//!         .read_view("full_view")
//!         .write_view("full_view"))
//!
//!     // Define views
//!     .view("system_view", |v| v
//!         .include(oid!(1, 3, 6, 1, 2, 1, 1)))  // system MIB only
//!     .view("full_view", |v| v
//!         .include(oid!(1, 3, 6, 1)))           // everything
//!     .view("if_admin_view", |v| v
//!         .include(oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 7)))  // ifAdminStatus
//!     .build();
//! # }
//! ```
//!
//! # View Exclusions
//!
//! Views can exclude specific subtrees from a broader include:
//!
//! ```rust
//! use async_snmp::agent::View;
//! use async_snmp::oid;
//!
//! // Include all of system MIB except sysServices
//! let view = View::new()
//!     .include(oid!(1, 3, 6, 1, 2, 1, 1))        // system MIB
//!     .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 7));    // except sysServices
//!
//! assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)));   // sysDescr.0 - allowed
//! assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 7, 0)));  // sysServices.0 - blocked
//! ```
//!
//! # Wildcard Masks
//!
//! Masks allow matching OIDs with wildcards at specific positions:
//!
//! ```rust
//! use async_snmp::agent::ViewSubtree;
//! use async_snmp::oid;
//!
//! // Match ifDescr for any interface index (ifDescr.*)
//! // OID: 1.3.6.1.2.1.2.2.1.2 (10 arcs, indices 0-9)
//! // Mask: 0xFF 0xC0 = 11111111 11000000 (arcs 0-9 must match, 10+ wildcard)
//! let subtree = ViewSubtree {
//!     oid: oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2),  // ifDescr
//!     mask: vec![0xFF, 0xC0],
//!     included: true,
//! };
//!
//! // Matches any interface index
//! assert!(subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 1)));    // ifDescr.1
//! assert!(subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 100)));  // ifDescr.100
//!
//! // Does not match different columns
//! assert!(!subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 3, 1)));   // ifType.1
//! ```
//!
//! # Integration with Agent
//!
//! Use [`AgentBuilder::vacm()`](super::AgentBuilder::vacm) to configure VACM:
//!
//! ```rust,no_run
//! use async_snmp::agent::{Agent, SecurityModel};
//! use async_snmp::oid;
//!
//! # async fn example() -> Result<(), Box<async_snmp::Error>> {
//! let agent = Agent::builder()
//!     .bind("0.0.0.0:161")
//!     .community(b"public")
//!     .community(b"private")
//!     .vacm(|v| v
//!         .group("public", SecurityModel::V2c, "readonly")
//!         .group("private", SecurityModel::V2c, "readwrite")
//!         .access("readonly", |a| a.read_view("all"))
//!         .access("readwrite", |a| a.read_view("all").write_view("all"))
//!         .view("all", |v| v.include(oid!(1, 3, 6, 1))))
//!     .build()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Access Denied Behavior
//!
//! When VACM denies access:
//! - **SNMPv1**: Returns `noSuchName` error
//! - **SNMPv2c/v3 GET**: Returns `noAccess` error or `NoSuchObject` per RFC 3416
//! - **SNMPv2c/v3 SET**: Returns `noAccess` error

use std::collections::HashMap;

use bytes::Bytes;

use crate::message::SecurityLevel;
use crate::oid::Oid;

pub use crate::handler::SecurityModel;

/// Context matching mode for access entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ContextMatch {
    /// Exact context name match.
    #[default]
    Exact,
    /// Context name prefix match.
    Prefix,
}

/// Result of checking whether a subtree is in a view.
///
/// This 3-state result enables optimizations for GETBULK/GETNEXT operations
/// by distinguishing between definite inclusion, definite exclusion, and
/// mixed/ambiguous subtrees that require per-OID checking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViewCheckResult {
    /// The queried OID and all its descendants are definitely in the view.
    Included,
    /// The queried OID and all its descendants are definitely not in the view.
    Excluded,
    /// The subtree has mixed permissions - some descendants are included,
    /// others are excluded. Per-OID access checks are required.
    Ambiguous,
}

/// A view is a collection of OID subtrees defining accessible objects.
///
/// Views are used by VACM to determine which OIDs a user can access.
/// Each view consists of included and/or excluded subtrees.
///
/// # Example
///
/// ```rust
/// use async_snmp::agent::View;
/// use async_snmp::oid;
///
/// // Create a view that includes the system MIB but excludes sysContact
/// let view = View::new()
///     .include(oid!(1, 3, 6, 1, 2, 1, 1))        // system MIB
///     .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 4));    // sysContact
///
/// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)));   // sysDescr.0
/// assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 4, 0)));  // sysContact.0
/// assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 2)));        // interfaces MIB
/// ```
#[derive(Debug, Clone, Default)]
pub struct View {
    subtrees: Vec<ViewSubtree>,
}

impl View {
    /// Create a new empty view.
    ///
    /// An empty view contains no OIDs. Add subtrees with [`include()`](View::include)
    /// or [`exclude()`](View::exclude).
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an included subtree to the view.
    ///
    /// All OIDs starting with `oid` will be included in the view,
    /// unless excluded by a later [`exclude()`](View::exclude) call.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::View;
    /// use async_snmp::oid;
    ///
    /// let view = View::new()
    ///     .include(oid!(1, 3, 6, 1, 2, 1))  // MIB-2
    ///     .include(oid!(1, 3, 6, 1, 4, 1)); // enterprises
    ///
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 4, 1, 99999, 1)));
    /// ```
    pub fn include(mut self, oid: Oid) -> Self {
        self.subtrees.push(ViewSubtree {
            oid,
            mask: Vec::new(),
            included: true,
        });
        self
    }

    /// Add an included subtree with a wildcard mask.
    ///
    /// The mask allows wildcards at specific OID arc positions.
    /// See [`ViewSubtree::mask`] for mask format details.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::View;
    /// use async_snmp::oid;
    ///
    /// // Include ifDescr for any interface (mask makes arc 10 a wildcard)
    /// let view = View::new()
    ///     .include_masked(
    ///         oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2),  // ifDescr
    ///         vec![0xFF, 0xC0]  // First 10 arcs must match
    ///     );
    ///
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 1)));   // ifDescr.1
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 100))); // ifDescr.100
    /// ```
    pub fn include_masked(mut self, oid: Oid, mask: Vec<u8>) -> Self {
        self.subtrees.push(ViewSubtree {
            oid,
            mask,
            included: true,
        });
        self
    }

    /// Add an excluded subtree to the view.
    ///
    /// OIDs starting with `oid` will be excluded, even if they match
    /// an included subtree. Exclusions take precedence.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::View;
    /// use async_snmp::oid;
    ///
    /// let view = View::new()
    ///     .include(oid!(1, 3, 6, 1, 2, 1, 1))     // system MIB
    ///     .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 6)); // except sysLocation
    ///
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)));  // sysDescr
    /// assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 6, 0))); // sysLocation
    /// ```
    pub fn exclude(mut self, oid: Oid) -> Self {
        self.subtrees.push(ViewSubtree {
            oid,
            mask: Vec::new(),
            included: false,
        });
        self
    }

    /// Add an excluded subtree with a wildcard mask.
    ///
    /// See [`include_masked()`](View::include_masked) for mask usage.
    pub fn exclude_masked(mut self, oid: Oid, mask: Vec<u8>) -> Self {
        self.subtrees.push(ViewSubtree {
            oid,
            mask,
            included: false,
        });
        self
    }

    /// Check if an OID is in this view.
    ///
    /// Per RFC 3415 Section 5, when multiple subtrees match an OID,
    /// the longest matching subtree determines inclusion/exclusion.
    /// At equal lengths, exclude wins.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::View;
    /// use async_snmp::oid;
    ///
    /// let view = View::new()
    ///     .include(oid!(1, 3, 6, 1, 2, 1))
    ///     .exclude(oid!(1, 3, 6, 1, 2, 1, 25));  // host resources
    ///
    /// assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
    /// assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 25, 1, 0)));
    /// assert!(!view.contains(&oid!(1, 3, 6, 1, 4, 1)));  // not included
    /// ```
    pub fn contains(&self, oid: &Oid) -> bool {
        let mut best_len: Option<usize> = None;
        let mut best_included = false;

        for subtree in &self.subtrees {
            if subtree.matches(oid) {
                let len = subtree.oid.len();
                match best_len {
                    Some(prev) if len < prev => {}
                    Some(prev) if len == prev && !subtree.included => {
                        // Equal length: exclude wins (conservative)
                        best_included = false;
                    }
                    _ => {
                        best_len = Some(len);
                        best_included = subtree.included;
                    }
                }
            }
        }

        best_included
    }

    /// Check subtree access status with 3-state result.
    ///
    /// Unlike [`contains()`](View::contains) which checks a single OID,
    /// this method determines the access status for an entire subtree.
    /// This enables optimizations for GETBULK/GETNEXT operations.
    ///
    /// Returns:
    /// - [`ViewCheckResult::Included`]: OID and all descendants are accessible
    /// - [`ViewCheckResult::Excluded`]: OID and all descendants are not accessible
    /// - [`ViewCheckResult::Ambiguous`]: Mixed permissions, check each OID individually
    pub fn check_subtree(&self, oid: &Oid) -> ViewCheckResult {
        // Find the longest covering match (RFC 3415 longest-match semantics)
        let mut best_covering_len: Option<usize> = None;
        let mut best_covering_included = false;
        let mut has_child_include = false;
        let mut has_child_exclude = false;

        let query_arcs = oid.arcs();

        for subtree in &self.subtrees {
            if subtree.matches(oid) {
                let len = subtree.oid.len();
                match best_covering_len {
                    Some(prev) if len < prev => {}
                    Some(prev) if len == prev && !subtree.included => {
                        best_covering_included = false;
                    }
                    _ => {
                        best_covering_len = Some(len);
                        best_covering_included = subtree.included;
                    }
                }
            }

            let subtree_arcs = subtree.oid.arcs();
            if subtree_arcs.len() > query_arcs.len()
                && subtree_arcs[..query_arcs.len()] == *query_arcs
            {
                if subtree.included {
                    has_child_include = true;
                } else {
                    has_child_exclude = true;
                }
            }
        }

        match (best_covering_len.is_some(), best_covering_included) {
            (true, false) => {
                if has_child_include {
                    return ViewCheckResult::Ambiguous;
                }
                return ViewCheckResult::Excluded;
            }
            (true, true) => {
                if has_child_exclude {
                    return ViewCheckResult::Ambiguous;
                }
                return ViewCheckResult::Included;
            }
            _ => {}
        }

        if has_child_include {
            return ViewCheckResult::Ambiguous;
        }

        ViewCheckResult::Excluded
    }
}

/// A subtree in a view with optional mask.
#[derive(Debug, Clone)]
pub struct ViewSubtree {
    /// Base OID of subtree.
    pub oid: Oid,
    /// Bit mask for wildcard matching (empty = exact match).
    ///
    /// Each bit position corresponds to an arc in the OID:
    /// - Bit 7 (MSB) of byte 0 = arc 0
    /// - Bit 6 of byte 0 = arc 1
    /// - etc.
    ///
    /// A bit value of 1 means the arc must match exactly.
    /// A bit value of 0 means any value is accepted (wildcard).
    pub mask: Vec<u8>,
    /// Include (true) or exclude (false) this subtree.
    pub included: bool,
}

impl ViewSubtree {
    /// Check if an OID matches this subtree (with mask).
    pub fn matches(&self, oid: &Oid) -> bool {
        let subtree_arcs = self.oid.arcs();
        let oid_arcs = oid.arcs();

        // OID must be at least as long as subtree
        if oid_arcs.len() < subtree_arcs.len() {
            return false;
        }

        // Check each arc against mask
        for (i, &subtree_arc) in subtree_arcs.iter().enumerate() {
            let mask_bit = if i / 8 < self.mask.len() {
                (self.mask[i / 8] >> (7 - (i % 8))) & 1
            } else {
                1 // Default: exact match required
            };

            if mask_bit == 1 && oid_arcs[i] != subtree_arc {
                return false;
            }
            // mask_bit == 0: wildcard, any value matches
        }

        true
    }
}

/// Access table entry.
#[derive(Debug, Clone)]
pub struct VacmAccessEntry {
    /// Group name this entry applies to.
    pub group_name: Bytes,
    /// Context prefix for matching.
    pub context_prefix: Bytes,
    /// Security model (or Any for wildcard).
    pub security_model: SecurityModel,
    /// Minimum security level required.
    pub security_level: SecurityLevel,
    /// Context matching mode.
    pub(crate) context_match: ContextMatch,
    /// View name for read access.
    pub read_view: Bytes,
    /// View name for write access.
    pub write_view: Bytes,
    /// View name for notify access (traps/informs).
    pub notify_view: Bytes,
}

/// Builder for access entries.
///
/// Configure what views a group can access for different operations.
/// Typically used via [`VacmBuilder::access()`].
///
/// # Example
///
/// ```rust
/// use async_snmp::agent::{SecurityModel, VacmBuilder};
/// use async_snmp::message::SecurityLevel;
/// use async_snmp::oid;
///
/// let vacm = VacmBuilder::new()
///     .group("admin", SecurityModel::Usm, "admin_group")
///     .access("admin_group", |a| a
///         .security_model(SecurityModel::Usm)
///         .security_level(SecurityLevel::AuthPriv)
///         .read_view("full_view")
///         .write_view("config_view")
///         .notify_view("trap_view"))
///     .view("full_view", |v| v.include(oid!(1, 3, 6, 1)))
///     .view("config_view", |v| v.include(oid!(1, 3, 6, 1, 4, 1)))
///     .view("trap_view", |v| v.include(oid!(1, 3, 6, 1)))
///     .build();
/// ```
pub struct AccessEntryBuilder {
    group_name: Bytes,
    context_prefix: Bytes,
    security_model: SecurityModel,
    security_level: SecurityLevel,
    context_match: ContextMatch,
    read_view: Bytes,
    write_view: Bytes,
    notify_view: Bytes,
}

impl AccessEntryBuilder {
    /// Create a new access entry builder for a group.
    pub fn new(group_name: impl Into<Bytes>) -> Self {
        Self {
            group_name: group_name.into(),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::new(),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        }
    }

    /// Set the context prefix for matching.
    ///
    /// Context is an SNMPv3 concept that allows partitioning MIB views.
    /// Most deployments use an empty context (the default).
    pub fn context_prefix(mut self, prefix: impl Into<Bytes>) -> Self {
        self.context_prefix = prefix.into();
        self
    }

    /// Set the security model this entry applies to.
    ///
    /// Default is [`SecurityModel::Any`] which matches all models.
    pub fn security_model(mut self, model: SecurityModel) -> Self {
        self.security_model = model;
        self
    }

    /// Set the minimum security level required.
    ///
    /// Requests with lower security levels will be denied access.
    /// Default is [`SecurityLevel::NoAuthNoPriv`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::{SecurityModel, VacmBuilder};
    /// use async_snmp::message::SecurityLevel;
    /// use async_snmp::oid;
    ///
    /// let vacm = VacmBuilder::new()
    ///     .group("admin", SecurityModel::Usm, "secure_group")
    ///     .access("secure_group", |a| a
    ///         // Require authentication and encryption
    ///         .security_level(SecurityLevel::AuthPriv)
    ///         .read_view("full_view"))
    ///     .view("full_view", |v| v.include(oid!(1, 3, 6, 1)))
    ///     .build();
    /// ```
    pub fn security_level(mut self, level: SecurityLevel) -> Self {
        self.security_level = level;
        self
    }

    /// Set context matching to prefix mode.
    ///
    /// When enabled, the context prefix is matched against the start of
    /// the request context name rather than requiring an exact match.
    /// The default is exact matching.
    pub fn context_match_prefix(mut self) -> Self {
        self.context_match = ContextMatch::Prefix;
        self
    }

    /// Set the read view name.
    ///
    /// The view must be defined with [`VacmBuilder::view()`].
    /// If not set, read operations are denied.
    pub fn read_view(mut self, view: impl Into<Bytes>) -> Self {
        self.read_view = view.into();
        self
    }

    /// Set the write view name.
    ///
    /// The view must be defined with [`VacmBuilder::view()`].
    /// If not set, write (SET) operations are denied.
    pub fn write_view(mut self, view: impl Into<Bytes>) -> Self {
        self.write_view = view.into();
        self
    }

    /// Set the notify view name.
    ///
    /// Used for trap/inform generation (not access control).
    /// The view must be defined with [`VacmBuilder::view()`].
    pub fn notify_view(mut self, view: impl Into<Bytes>) -> Self {
        self.notify_view = view.into();
        self
    }

    /// Build the access entry.
    pub fn build(self) -> VacmAccessEntry {
        VacmAccessEntry {
            group_name: self.group_name,
            context_prefix: self.context_prefix,
            security_model: self.security_model,
            security_level: self.security_level,
            context_match: self.context_match,
            read_view: self.read_view,
            write_view: self.write_view,
            notify_view: self.notify_view,
        }
    }
}

/// VACM configuration.
#[derive(Debug, Clone, Default)]
pub struct VacmConfig {
    /// (securityModel, securityName) → groupName
    security_to_group: HashMap<(SecurityModel, Bytes), Bytes>,
    /// Access table entries.
    access_entries: Vec<VacmAccessEntry>,
    /// viewName → View
    views: HashMap<Bytes, View>,
}

impl VacmConfig {
    /// Create a new empty VACM configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Map a security name to a group for a specific security model.
    pub fn add_group(
        &mut self,
        security_name: impl Into<Bytes>,
        security_model: SecurityModel,
        group_name: impl Into<Bytes>,
    ) {
        self.security_to_group
            .insert((security_model, security_name.into()), group_name.into());
    }

    /// Add an access entry.
    pub fn add_access(&mut self, entry: VacmAccessEntry) {
        self.access_entries.push(entry);
    }

    /// Add a view.
    pub fn add_view(&mut self, name: impl Into<Bytes>, view: View) {
        self.views.insert(name.into(), view);
    }

    /// Resolve group name for a request.
    pub fn get_group(&self, model: SecurityModel, name: &[u8]) -> Option<&Bytes> {
        // Try exact model match first, then fall back to Any.
        // Iterate to avoid allocating a Bytes for the lookup key.
        let mut any_match = None;
        for ((entry_model, entry_name), group) in &self.security_to_group {
            if entry_name.as_ref() == name {
                if *entry_model == model {
                    return Some(group);
                } else if *entry_model == SecurityModel::Any {
                    any_match = Some(group);
                }
            }
        }
        any_match
    }

    /// Get access entry for context.
    ///
    /// Returns the best matching entry per RFC 3415 Section 4 (vacmAccessTable DESCRIPTION).
    /// Selection uses a 4-tier preference order:
    /// 1. Prefer specific securityModel over Any
    /// 2. Prefer exact contextMatch over prefix
    /// 3. Prefer longer contextPrefix
    /// 4. Prefer higher securityLevel
    pub fn get_access(
        &self,
        group: &[u8],
        context: &[u8],
        model: SecurityModel,
        level: SecurityLevel,
    ) -> Option<&VacmAccessEntry> {
        self.access_entries
            .iter()
            .filter(|e| {
                e.group_name.as_ref() == group
                    && self.context_matches(&e.context_prefix, context, e.context_match)
                    && (e.security_model == model || e.security_model == SecurityModel::Any)
                    && level >= e.security_level
            })
            .max_by_key(|e| {
                // RFC 3415 Section 4 preference order (tuple comparison is lexicographic)
                let model_score: u8 = if e.security_model == model { 1 } else { 0 };
                let match_score: u8 = if e.context_match == ContextMatch::Exact {
                    1
                } else {
                    0
                };
                let prefix_len = e.context_prefix.len();
                let level_score = e.security_level as u8;
                (model_score, match_score, prefix_len, level_score)
            })
    }

    /// Check if context matches the prefix.
    fn context_matches(&self, prefix: &[u8], context: &[u8], mode: ContextMatch) -> bool {
        match mode {
            ContextMatch::Exact => prefix == context,
            ContextMatch::Prefix => context.starts_with(prefix),
        }
    }

    /// Check if OID access is permitted.
    pub fn check_access(&self, view_name: Option<&Bytes>, oid: &Oid) -> bool {
        let Some(view_name) = view_name else {
            return false;
        };

        if view_name.is_empty() {
            return false;
        }

        let Some(view) = self.views.get(view_name) else {
            return false;
        };

        view.contains(oid)
    }
}

/// Builder for VACM configuration.
///
/// Use this to configure access control for your SNMP agent. The typical
/// workflow is:
///
/// 1. Map security names (communities/usernames) to groups with [`group()`](VacmBuilder::group)
/// 2. Define access rules for groups with [`access()`](VacmBuilder::access)
/// 3. Define views (OID collections) with [`view()`](VacmBuilder::view)
/// 4. Build with [`build()`](VacmBuilder::build)
///
/// # Example
///
/// ```rust
/// use async_snmp::agent::{SecurityModel, VacmBuilder};
/// use async_snmp::message::SecurityLevel;
/// use async_snmp::oid;
///
/// let vacm = VacmBuilder::new()
///     // Step 1: Map security names to groups
///     .group("public", SecurityModel::V2c, "readers")
///     .group("admin", SecurityModel::Usm, "admins")
///
///     // Step 2: Define access for each group
///     .access("readers", |a| a
///         .read_view("system_view"))
///     .access("admins", |a| a
///         .security_level(SecurityLevel::AuthPriv)
///         .read_view("full_view")
///         .write_view("full_view"))
///
///     // Step 3: Define views
///     .view("system_view", |v| v
///         .include(oid!(1, 3, 6, 1, 2, 1, 1)))
///     .view("full_view", |v| v
///         .include(oid!(1, 3, 6, 1)))
///
///     // Step 4: Build
///     .build();
/// ```
pub struct VacmBuilder {
    config: VacmConfig,
}

impl VacmBuilder {
    /// Create a new VACM builder.
    pub fn new() -> Self {
        Self {
            config: VacmConfig::new(),
        }
    }

    /// Map a security name to a group.
    ///
    /// The security name is:
    /// - For SNMPv1/v2c: the community string
    /// - For SNMPv3: the USM username
    ///
    /// Multiple security names can map to the same group.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::{SecurityModel, VacmBuilder};
    ///
    /// let vacm = VacmBuilder::new()
    ///     // Multiple communities in same group
    ///     .group("public", SecurityModel::V2c, "readonly")
    ///     .group("monitor", SecurityModel::V2c, "readonly")
    ///     // Different users in different groups
    ///     .group("admin", SecurityModel::Usm, "admin_group")
    ///     .build();
    /// ```
    pub fn group(
        mut self,
        security_name: impl Into<Bytes>,
        security_model: SecurityModel,
        group_name: impl Into<Bytes>,
    ) -> Self {
        self.config
            .add_group(security_name, security_model, group_name);
        self
    }

    /// Add an access entry using a builder function.
    ///
    /// Access entries define what views a group can use for read, write,
    /// and notify operations. Use the closure to configure the entry.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::{SecurityModel, VacmBuilder};
    /// use async_snmp::message::SecurityLevel;
    /// use async_snmp::oid;
    ///
    /// let vacm = VacmBuilder::new()
    ///     .group("public", SecurityModel::V2c, "readers")
    ///     .access("readers", |a| a
    ///         .security_model(SecurityModel::V2c)
    ///         .security_level(SecurityLevel::NoAuthNoPriv)
    ///         .read_view("system_view")
    ///         // No write_view = read-only
    ///     )
    ///     .view("system_view", |v| v.include(oid!(1, 3, 6, 1, 2, 1, 1)))
    ///     .build();
    /// ```
    pub fn access<F>(mut self, group_name: impl Into<Bytes>, configure: F) -> Self
    where
        F: FnOnce(AccessEntryBuilder) -> AccessEntryBuilder,
    {
        let builder = AccessEntryBuilder::new(group_name);
        let entry = configure(builder).build();
        self.config.add_access(entry);
        self
    }

    /// Add a view using a builder function.
    ///
    /// Views define collections of OID subtrees. Use the closure to add
    /// included and excluded subtrees.
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_snmp::agent::VacmBuilder;
    /// use async_snmp::oid;
    ///
    /// let vacm = VacmBuilder::new()
    ///     .view("system_only", |v| v
    ///         .include(oid!(1, 3, 6, 1, 2, 1, 1)))  // system MIB
    ///     .view("all_except_private", |v| v
    ///         .include(oid!(1, 3, 6, 1))
    ///         .exclude(oid!(1, 3, 6, 1, 4, 1, 99999)))  // exclude our enterprise
    ///     .build();
    /// ```
    pub fn view<F>(mut self, name: impl Into<Bytes>, configure: F) -> Self
    where
        F: FnOnce(View) -> View,
    {
        let view = configure(View::new());
        self.config.add_view(name, view);
        self
    }

    /// Build the VACM configuration.
    pub fn build(self) -> VacmConfig {
        self.config
    }
}

impl Default for VacmBuilder {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_view_contains_simple() {
        let view = View::new().include(oid!(1, 3, 6, 1, 2, 1)); // system MIB

        // OID within the subtree
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 2, 1, 1)));

        // OID exactly at subtree
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1)));

        // OID outside the subtree
        assert!(!view.contains(&oid!(1, 3, 6, 1, 4, 1)));
        assert!(!view.contains(&oid!(1, 3, 6, 1, 2)));
    }

    #[test]
    fn test_view_exclude() {
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1)) // system MIB
            .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 7)); // sysServices

        // Included OIDs
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)));

        // Excluded OID
        assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 7)));
        assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 7, 0)));
    }

    #[test]
    fn test_view_longest_match_wins() {
        // RFC 3415 Section 5: when multiple subtrees match, longest match wins.
        // include(1.3.6.1) + exclude(1.3.6.1.2) + include(1.3.6.1.2.1)
        // For OID 1.3.6.1.2.1.1.0, all three match. Longest is include(1.3.6.1.2.1),
        // so the OID should be accessible.
        let view = View::new()
            .include(oid!(1, 3, 6, 1))
            .exclude(oid!(1, 3, 6, 1, 2))
            .include(oid!(1, 3, 6, 1, 2, 1));

        // Longest match is include(1.3.6.1.2.1), so this should be included
        assert!(view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));

        // OID under the exclude but not re-included
        assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 3, 1, 0)));

        // OID only under the top-level include, not under exclude
        assert!(view.contains(&oid!(1, 3, 6, 1, 4, 1, 0)));
    }

    #[test]
    fn test_view_longest_match_exclude_wins() {
        // When longest match is an exclude, OID should be excluded
        let view = View::new()
            .include(oid!(1, 3, 6, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1));

        assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
        assert!(view.contains(&oid!(1, 3, 6, 1, 4, 1, 0)));
    }

    #[test]
    fn test_view_equal_length_exclude_wins() {
        // When include and exclude have equal match length, exclude should win
        // (conservative interpretation: deny beats allow at same specificity)
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1));

        assert!(!view.contains(&oid!(1, 3, 6, 1, 2, 1, 1, 0)));
    }

    #[test]
    fn test_view_subtree_mask() {
        // Create a view that matches ifDescr.* (any interface index)
        // The subtree OID is ifDescr (1.3.6.1.2.1.2.2.1.2) with 10 arcs (indices 0-9)
        // We want arcs 0-9 to match exactly, and arc 10+ to be wildcard
        // Mask: 0xFF = 11111111 (arcs 0-7 must match)
        //       0xC0 = 11000000 (arcs 8-9 must match, 10-15 wildcard)
        let subtree = ViewSubtree {
            oid: oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2), // ifDescr
            mask: vec![0xFF, 0xC0],                  // 11111111 11000000 - arcs 0-9 must match
            included: true,
        };

        // Should match with any interface index in position 10
        assert!(subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 1)));
        assert!(subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 999)));

        // Should not match if arc 9 differs (the "2" in ifDescr)
        assert!(!subtree.matches(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 3, 1)));
    }

    #[test]
    fn test_vacm_group_lookup() {
        let mut config = VacmConfig::new();
        config.add_group("public", SecurityModel::V2c, "readonly_group");
        config.add_group("admin", SecurityModel::Usm, "admin_group");

        assert_eq!(
            config.get_group(SecurityModel::V2c, b"public"),
            Some(&Bytes::from_static(b"readonly_group"))
        );
        assert_eq!(
            config.get_group(SecurityModel::Usm, b"admin"),
            Some(&Bytes::from_static(b"admin_group"))
        );
        assert_eq!(config.get_group(SecurityModel::V1, b"public"), None);
    }

    #[test]
    fn test_vacm_group_any_model() {
        let mut config = VacmConfig::new();
        config.add_group("universal", SecurityModel::Any, "universal_group");

        // Should match any security model
        assert_eq!(
            config.get_group(SecurityModel::V1, b"universal"),
            Some(&Bytes::from_static(b"universal_group"))
        );
        assert_eq!(
            config.get_group(SecurityModel::V2c, b"universal"),
            Some(&Bytes::from_static(b"universal_group"))
        );
    }

    #[test]
    fn test_vacm_access_lookup() {
        let mut config = VacmConfig::new();
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"readonly_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"full_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        let access = config.get_access(
            b"readonly_group",
            b"",
            SecurityModel::V2c,
            SecurityLevel::NoAuthNoPriv,
        );
        assert!(access.is_some());
        assert_eq!(access.unwrap().read_view, Bytes::from_static(b"full_view"));
    }

    #[test]
    fn test_vacm_access_security_level() {
        let mut config = VacmConfig::new();
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"admin_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Usm,
            security_level: SecurityLevel::AuthPriv, // Require encryption
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"full_view"),
            write_view: Bytes::from_static(b"full_view"),
            notify_view: Bytes::new(),
        });

        // Should not match with lower security level
        let access = config.get_access(
            b"admin_group",
            b"",
            SecurityModel::Usm,
            SecurityLevel::AuthNoPriv,
        );
        assert!(access.is_none());

        // Should match with required level
        let access = config.get_access(
            b"admin_group",
            b"",
            SecurityModel::Usm,
            SecurityLevel::AuthPriv,
        );
        assert!(access.is_some());
    }

    #[test]
    fn test_vacm_check_access() {
        let mut config = VacmConfig::new();
        config.add_view("full_view", View::new().include(oid!(1, 3, 6, 1)));

        assert!(config.check_access(
            Some(&Bytes::from_static(b"full_view")),
            &oid!(1, 3, 6, 1, 2, 1, 1, 0),
        ));

        // Empty view name = no access
        assert!(!config.check_access(Some(&Bytes::new()), &oid!(1, 3, 6, 1, 2, 1, 1, 0),));

        // None = no access
        assert!(!config.check_access(None, &oid!(1, 3, 6, 1, 2, 1, 1, 0),));

        // Unknown view = no access
        assert!(!config.check_access(
            Some(&Bytes::from_static(b"unknown_view")),
            &oid!(1, 3, 6, 1, 2, 1, 1, 0),
        ));
    }

    #[test]
    fn test_vacm_builder() {
        let config = VacmBuilder::new()
            .group("public", SecurityModel::V2c, "readonly_group")
            .group("admin", SecurityModel::Usm, "admin_group")
            .access("readonly_group", |a| {
                a.context_prefix("")
                    .security_model(SecurityModel::Any)
                    .security_level(SecurityLevel::NoAuthNoPriv)
                    .read_view("full_view")
            })
            .access("admin_group", |a| {
                a.security_model(SecurityModel::Usm)
                    .security_level(SecurityLevel::AuthPriv)
                    .read_view("full_view")
                    .write_view("full_view")
            })
            .view("full_view", |v| v.include(oid!(1, 3, 6, 1)))
            .build();

        assert!(config.get_group(SecurityModel::V2c, b"public").is_some());
        assert!(config.get_group(SecurityModel::Usm, b"admin").is_some());
    }

    // RFC 3415 Section 4 preference order tests
    // The vacmAccessTable DESCRIPTION specifies a 4-tier preference order:
    // 1. Prefer specific securityModel over Any
    // 2. Prefer exact contextMatch over prefix
    // 3. Prefer longer contextPrefix
    // 4. Prefer higher securityLevel

    #[test]
    fn test_vacm_access_prefers_specific_security_model_over_any() {
        // Tier 1: Specific securityModel should be preferred over Any
        let mut config = VacmConfig::new();

        // Add entry with Any security model
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"any_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Add entry with specific V2c security model
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::V2c,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"v2c_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query with V2c - should get the specific V2c entry
        let access = config
            .get_access(
                b"test_group",
                b"",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"v2c_view"),
            "should prefer specific security model over Any"
        );
    }

    #[test]
    fn test_vacm_access_prefers_exact_context_match_over_prefix() {
        // Tier 2: Exact contextMatch should be preferred over prefix match
        let mut config = VacmConfig::new();

        // Add entry with prefix context match
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"prefix_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Add entry with exact context match (same prefix)
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"exact_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query with exact context "ctx" - should get the exact match entry
        let access = config
            .get_access(
                b"test_group",
                b"ctx",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"exact_view"),
            "should prefer exact context match over prefix"
        );
    }

    #[test]
    fn test_vacm_access_prefers_longer_context_prefix() {
        // Tier 3: Longer contextPrefix should be preferred
        let mut config = VacmConfig::new();

        // Add entry with shorter context prefix
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"short_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Add entry with longer context prefix
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx_longer"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"long_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query with context that matches both - should get the longer prefix
        let access = config
            .get_access(
                b"test_group",
                b"ctx_longer_suffix",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"long_view"),
            "should prefer longer context prefix"
        );
    }

    #[test]
    fn test_vacm_access_prefers_higher_security_level() {
        // Tier 4: Higher securityLevel should be preferred
        let mut config = VacmConfig::new();

        // Add entry with NoAuthNoPriv
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"noauth_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Add entry with AuthNoPriv
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::AuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"auth_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Add entry with AuthPriv
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::AuthPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"authpriv_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query with AuthPriv - should get the AuthPriv entry (highest matching)
        let access = config
            .get_access(
                b"test_group",
                b"",
                SecurityModel::V2c,
                SecurityLevel::AuthPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"authpriv_view"),
            "should prefer higher security level"
        );
    }

    #[test]
    fn test_vacm_access_preference_tier_ordering() {
        // Test that tier 1 takes precedence over tier 2, which takes precedence
        // over tier 3, which takes precedence over tier 4.
        let mut config = VacmConfig::new();

        // Entry: Any model, prefix match, short prefix, high security
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::AuthPriv, // highest security
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"any_prefix_short_high"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Entry: Specific model, prefix match, short prefix, low security
        // Tier 1 (specific model) should beat tier 4 (high security)
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::V2c,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"v2c_prefix_short_low"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query - specific model (V2c) should win over Any even though Any has higher security
        let access = config
            .get_access(
                b"test_group",
                b"ctx_test",
                SecurityModel::V2c,
                SecurityLevel::AuthPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"v2c_prefix_short_low"),
            "tier 1 (specific model) should take precedence over tier 4 (security level)"
        );
    }

    #[test]
    fn test_vacm_access_preference_context_match_over_prefix_length() {
        // Tier 2 (exact match) should beat tier 3 (longer prefix)
        let mut config = VacmConfig::new();

        // Entry: prefix match with longer prefix
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"context"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"long_prefix_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Entry: exact match with shorter prefix
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"short_exact_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query with "ctx" - exact match should win even though it's shorter
        let access = config
            .get_access(
                b"test_group",
                b"ctx",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"short_exact_view"),
            "tier 2 (exact match) should take precedence over tier 3 (longer prefix)"
        );
    }

    #[test]
    fn test_vacm_access_preference_prefix_length_over_security() {
        // Tier 3 (longer prefix) should beat tier 4 (higher security)
        let mut config = VacmConfig::new();

        // Entry: short prefix with high security
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::AuthPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"short_high_sec"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Entry: longer prefix with low security
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx_test"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"long_low_sec"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Query - longer prefix should win even though short prefix has higher security
        let access = config
            .get_access(
                b"test_group",
                b"ctx_test_suffix",
                SecurityModel::V2c,
                SecurityLevel::AuthPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"long_low_sec"),
            "tier 3 (longer prefix) should take precedence over tier 4 (security level)"
        );
    }

    #[test]
    fn test_vacm_access_all_tiers_combined() {
        // Test with multiple entries that differ in all tiers
        let mut config = VacmConfig::new();

        // Entry 1: Any, prefix, short, NoAuth
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"a"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"entry1"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        // Entry 2: V2c (specific), exact, short, NoAuth - should win for "a" context
        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"a"),
            security_model: SecurityModel::V2c,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"entry2"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        let access = config
            .get_access(
                b"test_group",
                b"a",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"entry2"),
            "specific model + exact match should win"
        );
    }

    // Tests that verify preference ordering is independent of insertion order
    #[test]
    fn test_vacm_access_exact_wins_regardless_of_insertion_order() {
        // Add exact first, prefix second - exact should still win
        let mut config = VacmConfig::new();

        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"exact_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::from_static(b"ctx"),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Prefix,
            read_view: Bytes::from_static(b"prefix_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        let access = config
            .get_access(
                b"test_group",
                b"ctx",
                SecurityModel::V2c,
                SecurityLevel::NoAuthNoPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"exact_view"),
            "exact match should win regardless of insertion order"
        );
    }

    #[test]
    fn test_vacm_access_higher_security_wins_regardless_of_insertion_order() {
        // Add higher security first, lower second - higher should still win
        let mut config = VacmConfig::new();

        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::AuthPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"authpriv_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        config.add_access(VacmAccessEntry {
            group_name: Bytes::from_static(b"test_group"),
            context_prefix: Bytes::new(),
            security_model: SecurityModel::Any,
            security_level: SecurityLevel::NoAuthNoPriv,
            context_match: ContextMatch::Exact,
            read_view: Bytes::from_static(b"noauth_view"),
            write_view: Bytes::new(),
            notify_view: Bytes::new(),
        });

        let access = config
            .get_access(
                b"test_group",
                b"",
                SecurityModel::V2c,
                SecurityLevel::AuthPriv,
            )
            .expect("should find access entry");
        assert_eq!(
            access.read_view,
            Bytes::from_static(b"authpriv_view"),
            "higher security level should win regardless of insertion order"
        );
    }

    // ViewCheckResult and check_subtree tests
    //
    // These tests validate the 3-state subtree check semantics from RFC 3415.
    // For GETBULK/GETNEXT operations, knowing whether a subtree has mixed
    // permissions enables optimizations:
    // - Included: Skip per-OID access checks for descendants
    // - Excluded: Early termination, no descendants accessible
    // - Ambiguous: Must check each OID individually

    #[test]
    fn test_check_subtree_empty_view_is_excluded() {
        // Empty view contains nothing
        let view = View::new();
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_oid_within_included_subtree() {
        // OID that falls within an included subtree is included
        let view = View::new().include(oid!(1, 3, 6, 1, 2, 1));

        // OID within the subtree
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1, 0)),
            ViewCheckResult::Included
        );
        // OID exactly at subtree root
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1)),
            ViewCheckResult::Included
        );
    }

    #[test]
    fn test_check_subtree_oid_within_excluded_subtree() {
        // OID within an excluded subtree (after include) is excluded
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 7));

        // OID within the excluded subtree
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1, 7, 0)),
            ViewCheckResult::Excluded
        );
        // OID exactly at exclude root
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1, 7)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_oid_outside_all_subtrees() {
        // OID completely outside any defined subtree is excluded
        let view = View::new().include(oid!(1, 3, 6, 1, 2, 1));

        // Different branch entirely
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 4, 1)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_parent_of_single_include_is_ambiguous() {
        // Parent OID of an included subtree is ambiguous:
        // some children (the include) are accessible, others are not
        let view = View::new().include(oid!(1, 3, 6, 1, 2, 1));

        // Parent of the included subtree
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1)),
            ViewCheckResult::Ambiguous
        );
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6)),
            ViewCheckResult::Ambiguous
        );
    }

    #[test]
    fn test_check_subtree_parent_of_include_with_nested_exclude() {
        // View with include and nested exclude: parent is ambiguous
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1, 1, 7));

        // Parent of the include - ambiguous because it has included descendants
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1)),
            ViewCheckResult::Ambiguous
        );

        // The include root itself - ambiguous because it contains excluded subtree
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1)),
            ViewCheckResult::Ambiguous
        );

        // Between include root and exclude - ambiguous
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1)),
            ViewCheckResult::Ambiguous
        );
    }

    #[test]
    fn test_check_subtree_fully_included_child() {
        // When querying a subtree that is fully within an include,
        // with no excludes affecting it, it should be included
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1, 25)); // exclude host resources

        // sysDescr subtree - fully included, no excludes affect it
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1, 1)),
            ViewCheckResult::Included
        );

        // But the system group itself is ambiguous because hrMIB is excluded
        // Wait, hrMIB is .25, not under .1 - so system group should be included
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1)),
            ViewCheckResult::Included
        );
    }

    #[test]
    fn test_check_subtree_multiple_includes() {
        // Multiple disjoint includes - parent is ambiguous
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1, 1)) // system
            .include(oid!(1, 3, 6, 1, 2, 1, 2)); // interfaces

        // Parent of both - ambiguous (some children included, others not)
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1)),
            ViewCheckResult::Ambiguous
        );

        // Each individual include is fully included
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 1)),
            ViewCheckResult::Included
        );
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 2)),
            ViewCheckResult::Included
        );

        // Sibling not in any include is excluded
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 3)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_exclude_only_is_excluded() {
        // An exclude without a covering include excludes nothing
        // (exclude only has effect when there's a matching include)
        // Actually, per RFC 3415, an exclude without include means the OID
        // is simply not in the view at all (excluded)
        let view = View::new().exclude(oid!(1, 3, 6, 1, 2, 1, 1, 7));

        // Everything is excluded because there's no include
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1)),
            ViewCheckResult::Excluded
        );
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_with_mask() {
        // Masked subtree - parent is ambiguous due to partial match
        let view = View::new().include_masked(
            oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2), // ifDescr
            vec![0xFF, 0xC0],                   // arcs 0-9 exact, 10+ wildcard
        );

        // Within the masked include - included
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 1)),
            ViewCheckResult::Included
        );

        // Parent of the masked include - ambiguous
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 2)),
            ViewCheckResult::Ambiguous
        );

        // Sibling column (ifType) - excluded
        assert_eq!(
            view.check_subtree(&oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 3)),
            ViewCheckResult::Excluded
        );
    }

    #[test]
    fn test_check_subtree_vs_contains_consistency() {
        // Verify that check_subtree is consistent with contains:
        // If check_subtree returns Included, contains should return true
        // If check_subtree returns Excluded, contains should return false
        let view = View::new()
            .include(oid!(1, 3, 6, 1, 2, 1))
            .exclude(oid!(1, 3, 6, 1, 2, 1, 25));

        let test_cases = [
            oid!(1, 3, 6, 1, 2, 1, 1, 0),  // included
            oid!(1, 3, 6, 1, 2, 1, 25, 1), // excluded
            oid!(1, 3, 6, 1, 4, 1),        // not in view at all
        ];

        for oid in &test_cases {
            let check_result = view.check_subtree(oid);
            let contains_result = view.contains(oid);

            match check_result {
                ViewCheckResult::Included => {
                    assert!(
                        contains_result,
                        "check_subtree=Included but contains=false for {:?}",
                        oid
                    );
                }
                ViewCheckResult::Excluded => {
                    assert!(
                        !contains_result,
                        "check_subtree=Excluded but contains=true for {:?}",
                        oid
                    );
                }
                ViewCheckResult::Ambiguous => {
                    // Ambiguous can be either, depending on specific OID
                }
            }
        }
    }
}