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
//! Container-based interoperability tests.
//!
//! These tests verify Client works correctly against net-snmp,
//! serving as the firewall against correlated bugs where both
//! Client and Agent might have the same flaw.
//!
//! Run with: cargo test --test interop

use std::net::SocketAddr;
use std::sync::OnceLock;
use std::time::Duration;

use async_snmp::{Auth, AuthProtocol, Client, PrivProtocol, Retry, UdpTransport, Value, oid};
use testcontainers::{
    ContainerAsync, GenericImage,
    core::{IntoContainerPort, WaitFor},
    runners::AsyncRunner,
};
use tokio::sync::OnceCell;

// ============================================================================
// Container Runtime Detection
// ============================================================================

/// Check if Docker is available.
fn is_docker_available() -> bool {
    static AVAILABLE: OnceLock<bool> = OnceLock::new();

    *AVAILABLE.get_or_init(|| {
        if std::env::var("DOCKER_HOST").is_ok() {
            return true;
        }

        let docker_paths = [
            "/var/run/docker.sock".to_string(),
            dirs::runtime_dir()
                .map(|d| format!("{}/.docker/run/docker.sock", d.display()))
                .unwrap_or_default(),
            dirs::home_dir()
                .map(|d| format!("{}/.docker/run/docker.sock", d.display()))
                .unwrap_or_default(),
            dirs::home_dir()
                .map(|d| format!("{}/.docker/desktop/docker.sock", d.display()))
                .unwrap_or_default(),
        ];

        docker_paths
            .iter()
            .any(|path| !path.is_empty() && std::path::Path::new(path).exists())
    })
}

macro_rules! require_container_runtime {
    () => {
        if !is_docker_available() {
            eprintln!("Skipping test: Docker not available");
            return;
        }
    };
}

// ============================================================================
// Shared Container Infrastructure
// ============================================================================

struct ContainerInfo {
    _container: ContainerAsync<GenericImage>,
    host: String,
    udp_port: u16,
    tcp_port: u16,
}

static SNMPD_CONTAINER: OnceCell<ContainerInfo> = OnceCell::const_new();

fn check_image_exists(image: &str) -> Result<(), String> {
    let output = std::process::Command::new("docker")
        .args(["image", "inspect", image])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match output {
        Ok(status) if status.success() => Ok(()),
        _ => Err(format!(
            "Container image '{image}' not found locally.\n\n\
            Build it before running tests:\n\n    \
            docker build -t {image} tests/containers/snmpd/\n"
        )),
    }
}

fn snmpd_image() -> String {
    std::env::var("SNMPD_IMAGE").unwrap_or_else(|_| "async-snmp-test:latest".to_string())
}

fn parse_image(image: &str) -> (&str, &str) {
    if let Some(idx) = image.rfind(':') {
        let after_colon = &image[idx + 1..];
        if !after_colon.contains('/') {
            return (&image[..idx], after_colon);
        }
    }
    (image, "latest")
}

async fn get_snmpd_container() -> &'static ContainerInfo {
    SNMPD_CONTAINER
        .get_or_init(|| async {
            let image_str = snmpd_image();
            let (name, tag) = parse_image(&image_str);

            if let Err(msg) = check_image_exists(&image_str) {
                panic!("{msg}");
            }

            // Use log-based waiting: entrypoint.sh outputs "SNMPD_READY" when snmpd is responsive
            let container = GenericImage::new(name, tag)
                .with_exposed_port(161.udp())
                .with_exposed_port(161.tcp())
                .with_wait_for(WaitFor::message_on_stdout("SNMPD_READY"))
                .start()
                .await
                .expect("Failed to start snmpd container");

            #[cfg(not(target_os = "linux"))]
            tokio::time::sleep(Duration::from_millis(4000)).await; // Wait a moment for host port forwarding to be ready

            let host = container.get_host().await.expect("Failed to get host");
            let udp_port = container
                .get_host_port_ipv4(161.udp())
                .await
                .expect("Failed to get UDP port");
            let tcp_port = container
                .get_host_port_ipv4(161.tcp())
                .await
                .expect("Failed to get TCP port");

            ContainerInfo {
                _container: container,
                host: host.to_string(),
                udp_port,
                tcp_port,
            }
        })
        .await
}

fn parse_target(info: &ContainerInfo) -> SocketAddr {
    use std::net::ToSocketAddrs;
    format!("{}:{}", info.host, info.udp_port)
        .to_socket_addrs()
        .expect("Failed to resolve target")
        .next()
        .expect("No addresses resolved")
}

// ============================================================================
// Test credentials (must match container configuration)
// ============================================================================

const COMMUNITY: &str = "public";
const AUTH_PASS: &str = "authpass123";
const PRIV_PASS: &str = "privpass123";

mod users {
    pub const NOAUTH_USER: &str = "noauth_user";
    #[cfg(feature = "crypto-rustcrypto")]
    pub const AUTHMD5_USER: &str = "authmd5_user";
    pub const AUTHSHA1_USER: &str = "authsha1_user";
    pub const AUTHSHA256_USER: &str = "authsha256_user";
    #[cfg(feature = "crypto-rustcrypto")]
    pub const PRIVDES_USER: &str = "privdes_user";
    pub const PRIVAES128_USER: &str = "privaes128_user";
}

// ============================================================================
// Basic Protocol Tests
// ============================================================================

#[tokio::test]
async fn v2c_get_returns_value() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .timeout(Duration::from_secs(5))
        .connect()
        .await
        .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();

    // sysDescr should be a non-empty string
    assert!(matches!(result.value, Value::OctetString(_)));
    if let Value::OctetString(s) = &result.value {
        assert!(!s.is_empty());
    }
}

#[tokio::test]
async fn v1_get_returns_value() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v1(COMMUNITY))
        .timeout(Duration::from_secs(5))
        .connect()
        .await
        .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();

    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn getnext_returns_next_oid() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    let result = client
        .get_next(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0))
        .await
        .unwrap();

    // Should return an OID greater than the request
    assert!(result.oid > oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));
}

#[tokio::test]
async fn getbulk_returns_multiple() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    let results = client
        .get_bulk(&[oid!(1, 3, 6, 1, 2, 1, 1)], 0, 5)
        .await
        .unwrap();

    assert!(results.len() >= 2);
}

// ============================================================================
// WALK Tests
// ============================================================================

#[tokio::test]
async fn walk_system_mib() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    let results = client
        .walk(oid!(1, 3, 6, 1, 2, 1, 1))
        .expect("walk creation failed")
        .collect()
        .await
        .expect("walk failed");

    assert!(!results.is_empty());
    for vb in &results {
        assert!(vb.oid.starts_with(&oid!(1, 3, 6, 1, 2, 1, 1)));
    }
}

#[tokio::test]
async fn bulk_walk_interfaces() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    let results = client
        .bulk_walk(oid!(1, 3, 6, 1, 2, 1, 2), 25)
        .collect()
        .await
        .expect("bulk_walk failed");

    assert!(!results.is_empty());
}

// ============================================================================
// V3 Security Level Tests
// ============================================================================

#[tokio::test]
async fn v3_no_auth_no_priv() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::usm(users::NOAUTH_USER))
        .timeout(Duration::from_secs(5))
        .connect()
        .await
        .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn v3_auth_no_priv() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::AUTHSHA256_USER).auth(AuthProtocol::Sha256, AUTH_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn v3_auth_priv() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::PRIVAES128_USER)
            .auth(AuthProtocol::Sha1, AUTH_PASS)
            .privacy(PrivProtocol::Aes128, PRIV_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

// ============================================================================
// V3 Auth Protocol Tests
// ============================================================================

#[cfg(feature = "crypto-rustcrypto")]
#[tokio::test]
async fn v3_auth_md5() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::AUTHMD5_USER).auth(AuthProtocol::Md5, AUTH_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn v3_auth_sha1() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::AUTHSHA1_USER).auth(AuthProtocol::Sha1, AUTH_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn v3_auth_sha256() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::AUTHSHA256_USER).auth(AuthProtocol::Sha256, AUTH_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

// ============================================================================
// V3 Priv Protocol Tests
// ============================================================================

#[cfg(feature = "crypto-rustcrypto")]
#[tokio::test]
async fn v3_priv_des() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::PRIVDES_USER)
            .auth(AuthProtocol::Sha1, AUTH_PASS)
            .privacy(PrivProtocol::Des, PRIV_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

#[tokio::test]
async fn v3_priv_aes128() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(
        &target,
        Auth::usm(users::PRIVAES128_USER)
            .auth(AuthProtocol::Sha1, AUTH_PASS)
            .privacy(PrivProtocol::Aes128, PRIV_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result.value, Value::OctetString(_)));
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn missing_oid_returns_no_such() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 99, 99, 99, 99)).await.unwrap();

    // Should be NoSuchObject or NoSuchInstance
    assert!(matches!(
        result.value,
        Value::NoSuchObject | Value::NoSuchInstance
    ));
}

#[tokio::test]
async fn wrong_community_fails() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c("wrongcommunity"))
        .timeout(Duration::from_secs(2))
        .retry(Retry::none())
        .connect()
        .await
        .unwrap();

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await;

    // Should timeout (agent ignores bad community) or return error
    assert!(result.is_err());
}

// ============================================================================
// Value Type Tests (verify codec)
// ============================================================================

#[tokio::test]
async fn value_types_decode_correctly() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .connect()
        .await
        .unwrap();

    // Test various value types from standard MIBs
    let results = client
        .get_many(&[
            oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), // OctetString (sysDescr)
            oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), // OID (sysObjectID)
            oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), // TimeTicks (sysUpTime)
            oid!(1, 3, 6, 1, 2, 1, 1, 7, 0), // Integer (sysServices)
        ])
        .await
        .unwrap();

    assert!(matches!(results[0].value, Value::OctetString(_)));
    assert!(matches!(results[1].value, Value::ObjectIdentifier(_)));
    assert!(matches!(results[2].value, Value::TimeTicks(_)));
    assert!(matches!(results[3].value, Value::Integer(_)));
}

// ============================================================================
// Transport Tests
// ============================================================================

#[tokio::test]
async fn tcp_transport_get() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.tcp_port);

    let client = Client::builder(&target, Auth::v2c(COMMUNITY))
        .timeout(Duration::from_secs(5))
        .connect_tcp()
        .await
        .expect("Failed to connect via TCP");

    let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await;

    match result {
        Ok(vb) => {
            assert_eq!(vb.oid, oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));
            assert!(matches!(vb.value, Value::OctetString(_)));
        }
        Err(e) => panic!("TCP GET failed: {}", e),
    }
}

#[tokio::test]
async fn shared_transport_multiple_clients() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = parse_target(info);

    let bind_addr = if target.is_ipv6() {
        "[::]:0"
    } else {
        "0.0.0.0:0"
    };
    let shared = UdpTransport::builder()
        .bind(bind_addr)
        .build()
        .await
        .expect("Failed to bind shared transport");

    let client1 = Client::builder(target.to_string(), Auth::v2c(COMMUNITY))
        .timeout(Duration::from_secs(5))
        .build_with(&shared)
        .await
        .expect("Failed to build client1");

    let client2 = Client::builder(target.to_string(), Auth::v2c(COMMUNITY))
        .timeout(Duration::from_secs(5))
        .build_with(&shared)
        .await
        .expect("Failed to build client2");

    // Run concurrent requests
    let oid1 = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0); // sysDescr
    let oid2 = oid!(1, 3, 6, 1, 2, 1, 1, 5, 0); // sysName
    let (result1, result2) = tokio::join!(client1.get(&oid1), client2.get(&oid2));

    let vb1 = result1.expect("Client 1 GET failed");
    let vb2 = result2.expect("Client 2 GET failed");

    assert!(matches!(vb1.value, Value::OctetString(_)));
    assert!(matches!(vb2.value, Value::OctetString(_)));
}

// ============================================================================
// V3 Engine Discovery Tests
// ============================================================================

#[tokio::test]
async fn v3_engine_discovery_and_request() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    // This test verifies the full V3 flow: discovery + authenticated request
    let client = Client::builder(
        &target,
        Auth::usm(users::PRIVAES128_USER)
            .auth(AuthProtocol::Sha1, AUTH_PASS)
            .privacy(PrivProtocol::Aes128, PRIV_PASS),
    )
    .timeout(Duration::from_secs(5))
    .connect()
    .await
    .expect("V3 connection with discovery should succeed");

    // First request triggers engine discovery
    let result1 = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await.unwrap();
    assert!(matches!(result1.value, Value::OctetString(_)));

    // Second request uses cached engine state
    let result2 = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 5, 0)).await.unwrap();
    assert!(matches!(result2.value, Value::OctetString(_)));
}

// ============================================================================
// SET Operation Test
// ============================================================================

#[tokio::test]
async fn set_writable_oid() {
    require_container_runtime!();

    let info = get_snmpd_container().await;
    let target = format!("{}:{}", info.host, info.udp_port);

    let client = Client::builder(&target, Auth::v2c("private"))
        .timeout(Duration::from_secs(5))
        .connect()
        .await
        .unwrap();

    let new_contact = Value::OctetString("admin@example.com".into());

    // SET sysContact
    let result = client
        .set(&oid!(1, 3, 6, 1, 2, 1, 1, 4, 0), new_contact.clone())
        .await;

    match result {
        Ok(vb) => {
            assert_eq!(vb.oid, oid!(1, 3, 6, 1, 2, 1, 1, 4, 0));
            if let Value::OctetString(s) = &vb.value {
                assert_eq!(s.as_ref(), b"admin@example.com");
            }
        }
        Err(e) => match *e {
            async_snmp::Error::Snmp { .. } => {
                // NotWritable is acceptable if agent doesn't allow writes
            }
            _ => panic!("SET failed unexpectedly: {}", e),
        },
    }
}