async_snmp/client/builder.rs
1//! New unified client builder.
2//!
3//! This module provides the [`ClientBuilder`] type, a single entry point for
4//! constructing SNMP clients with any authentication mode (v1/v2c community
5//! or v3 USM).
6
7use std::net::{SocketAddr, ToSocketAddrs};
8use std::sync::Arc;
9use std::time::Duration;
10
11use bytes::Bytes;
12
13use crate::client::retry::Retry;
14use crate::client::walk::{OidOrdering, WalkMode};
15use crate::client::{
16 Auth, ClientConfig, CommunityVersion, DEFAULT_MAX_OIDS_PER_REQUEST, DEFAULT_MAX_REPETITIONS,
17 DEFAULT_TIMEOUT, UsmConfig,
18};
19use crate::error::{Error, Result};
20use crate::transport::{TcpTransport, Transport, UdpHandle, UdpTransport};
21use crate::v3::EngineCache;
22use crate::version::Version;
23
24use super::Client;
25
26/// Builder for constructing SNMP clients.
27///
28/// This is the single entry point for client construction. It supports all
29/// SNMP versions (v1, v2c, v3) through the [`Auth`] enum.
30///
31/// # Example
32///
33/// ```rust,no_run
34/// use async_snmp::{Auth, ClientBuilder, Retry};
35/// use std::time::Duration;
36///
37/// # async fn example() -> async_snmp::Result<()> {
38/// // Simple v2c client
39/// let client = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
40/// .connect().await?;
41///
42/// // v3 client with authentication
43/// let client = ClientBuilder::new("192.168.1.1:161",
44/// Auth::usm("admin").auth(async_snmp::AuthProtocol::Sha256, "password"))
45/// .timeout(Duration::from_secs(10))
46/// .retry(Retry::fixed(5, Duration::ZERO))
47/// .connect().await?;
48/// # Ok(())
49/// # }
50/// ```
51pub struct ClientBuilder {
52 target: String,
53 auth: Auth,
54 timeout: Duration,
55 retry: Retry,
56 max_oids_per_request: usize,
57 max_repetitions: u32,
58 walk_mode: WalkMode,
59 oid_ordering: OidOrdering,
60 max_walk_results: Option<usize>,
61 engine_cache: Option<Arc<EngineCache>>,
62}
63
64impl ClientBuilder {
65 /// Create a new client builder.
66 ///
67 /// # Arguments
68 ///
69 /// * `target` - The target address (e.g., "192.168.1.1:161")
70 /// * `auth` - Authentication configuration (community or USM)
71 ///
72 /// # Example
73 ///
74 /// ```rust,no_run
75 /// use async_snmp::{Auth, ClientBuilder};
76 ///
77 /// // Using Auth::default() for v2c with "public" community
78 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::default());
79 ///
80 /// // Using Auth::v1() for SNMPv1
81 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v1("private"));
82 ///
83 /// // Using Auth::usm() for SNMPv3
84 /// let builder = ClientBuilder::new("192.168.1.1:161",
85 /// Auth::usm("admin").auth(async_snmp::AuthProtocol::Sha256, "password"));
86 /// ```
87 pub fn new(target: impl Into<String>, auth: impl Into<Auth>) -> Self {
88 Self {
89 target: target.into(),
90 auth: auth.into(),
91 timeout: DEFAULT_TIMEOUT,
92 retry: Retry::default(),
93 max_oids_per_request: DEFAULT_MAX_OIDS_PER_REQUEST,
94 max_repetitions: DEFAULT_MAX_REPETITIONS,
95 walk_mode: WalkMode::Auto,
96 oid_ordering: OidOrdering::Strict,
97 max_walk_results: None,
98 engine_cache: None,
99 }
100 }
101
102 /// Set the request timeout (default: 5 seconds).
103 ///
104 /// This is the time to wait for a response before retrying or failing.
105 /// The total time for a request may be `timeout * (retries + 1)`.
106 ///
107 /// # Example
108 ///
109 /// ```rust
110 /// use async_snmp::{Auth, ClientBuilder};
111 /// use std::time::Duration;
112 ///
113 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
114 /// .timeout(Duration::from_secs(10));
115 /// ```
116 pub fn timeout(mut self, timeout: Duration) -> Self {
117 self.timeout = timeout;
118 self
119 }
120
121 /// Set the retry configuration (default: 3 retries, no backoff).
122 ///
123 /// On timeout, the client resends the request up to this many times before
124 /// returning an error. Retries are disabled for TCP (which handles
125 /// reliability at the transport layer).
126 ///
127 /// # Example
128 ///
129 /// ```rust
130 /// use async_snmp::{Auth, ClientBuilder, Retry};
131 /// use std::time::Duration;
132 ///
133 /// // No retries
134 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
135 /// .retry(Retry::none());
136 ///
137 /// // 5 retries with no delay (immediate retry on timeout)
138 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
139 /// .retry(Retry::fixed(5, Duration::ZERO));
140 ///
141 /// // Fixed delay between retries
142 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
143 /// .retry(Retry::fixed(3, Duration::from_millis(200)));
144 ///
145 /// // Exponential backoff with jitter
146 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
147 /// .retry(Retry::exponential(5)
148 /// .max_delay(Duration::from_secs(5))
149 /// .jitter(0.25));
150 /// ```
151 pub fn retry(mut self, retry: impl Into<Retry>) -> Self {
152 self.retry = retry.into();
153 self
154 }
155
156 /// Set the maximum OIDs per request (default: 10).
157 ///
158 /// Requests with more OIDs than this limit are automatically split
159 /// into multiple batches. Some devices have lower limits on the number
160 /// of OIDs they can handle in a single request.
161 ///
162 /// # Example
163 ///
164 /// ```rust
165 /// use async_snmp::{Auth, ClientBuilder};
166 ///
167 /// // For devices with limited request handling capacity
168 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
169 /// .max_oids_per_request(5);
170 ///
171 /// // For high-capacity devices, increase to reduce round-trips
172 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
173 /// .max_oids_per_request(50);
174 /// ```
175 pub fn max_oids_per_request(mut self, max: usize) -> Self {
176 self.max_oids_per_request = max;
177 self
178 }
179
180 /// Set max-repetitions for GETBULK operations (default: 25).
181 ///
182 /// Controls how many values are requested per GETBULK PDU during walks.
183 /// This is a performance tuning parameter with trade-offs:
184 ///
185 /// - **Higher values**: Fewer network round-trips, faster walks on reliable
186 /// networks. But larger responses risk UDP fragmentation or may exceed
187 /// agent response buffer limits (causing truncation).
188 /// - **Lower values**: More round-trips (higher latency), but smaller
189 /// responses that fit within MTU limits.
190 ///
191 /// The default of 25 is conservative. For local/reliable networks with
192 /// capable agents, values of 50-100 can significantly speed up large walks.
193 ///
194 /// # Example
195 ///
196 /// ```rust
197 /// use async_snmp::{Auth, ClientBuilder};
198 ///
199 /// // Lower value for agents with small response buffers or lossy networks
200 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
201 /// .max_repetitions(10);
202 ///
203 /// // Higher value for fast local network walks
204 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
205 /// .max_repetitions(50);
206 /// ```
207 pub fn max_repetitions(mut self, max: u32) -> Self {
208 self.max_repetitions = max;
209 self
210 }
211
212 /// Override walk behavior for devices with buggy GETBULK (default: Auto).
213 ///
214 /// - `WalkMode::Auto`: Use GETNEXT for v1, GETBULK for v2c/v3
215 /// - `WalkMode::GetNext`: Always use GETNEXT (slower but more compatible)
216 /// - `WalkMode::GetBulk`: Always use GETBULK (faster, errors on v1)
217 ///
218 /// # Example
219 ///
220 /// ```rust
221 /// use async_snmp::{Auth, ClientBuilder, WalkMode};
222 ///
223 /// // Force GETNEXT for devices with broken GETBULK implementation
224 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
225 /// .walk_mode(WalkMode::GetNext);
226 ///
227 /// // Force GETBULK for faster walks (only v2c/v3)
228 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
229 /// .walk_mode(WalkMode::GetBulk);
230 /// ```
231 pub fn walk_mode(mut self, mode: WalkMode) -> Self {
232 self.walk_mode = mode;
233 self
234 }
235
236 /// Set OID ordering behavior for walk operations (default: Strict).
237 ///
238 /// - `OidOrdering::Strict`: Require strictly increasing OIDs. Most efficient.
239 /// - `OidOrdering::AllowNonIncreasing`: Allow non-increasing OIDs with cycle
240 /// detection. Uses O(n) memory to track seen OIDs.
241 ///
242 /// Use `AllowNonIncreasing` for buggy agents that return OIDs out of order.
243 ///
244 /// **Warning**: `AllowNonIncreasing` uses O(n) memory. Always pair with
245 /// [`max_walk_results`](Self::max_walk_results) to bound memory usage.
246 ///
247 /// # Example
248 ///
249 /// ```rust
250 /// use async_snmp::{Auth, ClientBuilder, OidOrdering};
251 ///
252 /// // Use relaxed ordering with a safety limit
253 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
254 /// .oid_ordering(OidOrdering::AllowNonIncreasing)
255 /// .max_walk_results(10_000);
256 /// ```
257 pub fn oid_ordering(mut self, ordering: OidOrdering) -> Self {
258 self.oid_ordering = ordering;
259 self
260 }
261
262 /// Set maximum results from a single walk operation (default: unlimited).
263 ///
264 /// Safety limit to prevent runaway walks. Walk terminates normally when
265 /// limit is reached.
266 ///
267 /// # Example
268 ///
269 /// ```rust
270 /// use async_snmp::{Auth, ClientBuilder};
271 ///
272 /// // Limit walks to at most 10,000 results
273 /// let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
274 /// .max_walk_results(10_000);
275 /// ```
276 pub fn max_walk_results(mut self, limit: usize) -> Self {
277 self.max_walk_results = Some(limit);
278 self
279 }
280
281 /// Set shared engine cache (V3 only, for polling many targets).
282 ///
283 /// Allows multiple clients to share discovered engine state, reducing
284 /// the number of discovery requests. This is particularly useful when
285 /// polling many devices with SNMPv3.
286 ///
287 /// # Example
288 ///
289 /// ```rust
290 /// use async_snmp::{Auth, AuthProtocol, ClientBuilder, EngineCache};
291 /// use std::sync::Arc;
292 ///
293 /// // Create a shared engine cache
294 /// let cache = Arc::new(EngineCache::new());
295 ///
296 /// // Multiple clients can share the same cache
297 /// let builder1 = ClientBuilder::new("192.168.1.1:161",
298 /// Auth::usm("admin").auth(AuthProtocol::Sha256, "password"))
299 /// .engine_cache(cache.clone());
300 ///
301 /// let builder2 = ClientBuilder::new("192.168.1.2:161",
302 /// Auth::usm("admin").auth(AuthProtocol::Sha256, "password"))
303 /// .engine_cache(cache.clone());
304 /// ```
305 pub fn engine_cache(mut self, cache: Arc<EngineCache>) -> Self {
306 self.engine_cache = Some(cache);
307 self
308 }
309
310 /// Validate the configuration.
311 fn validate(&self) -> Result<()> {
312 if let Auth::Usm(usm) = &self.auth {
313 // Privacy requires authentication
314 if usm.priv_protocol.is_some() && usm.auth_protocol.is_none() {
315 return Err(Error::Config("privacy requires authentication".into()).boxed());
316 }
317 // Protocol requires password (unless using master keys)
318 if usm.auth_protocol.is_some()
319 && usm.auth_password.is_none()
320 && usm.master_keys.is_none()
321 {
322 return Err(Error::Config("auth protocol requires password".into()).boxed());
323 }
324 if usm.priv_protocol.is_some()
325 && usm.priv_password.is_none()
326 && usm.master_keys.is_none()
327 {
328 return Err(Error::Config("priv protocol requires password".into()).boxed());
329 }
330 }
331
332 // Validate walk mode for v1
333 if let Auth::Community {
334 version: CommunityVersion::V1,
335 ..
336 } = &self.auth
337 && self.walk_mode == WalkMode::GetBulk
338 {
339 return Err(Error::Config("GETBULK not supported in SNMPv1".into()).boxed());
340 }
341
342 Ok(())
343 }
344
345 /// Resolve target address to SocketAddr.
346 fn resolve_target(&self) -> Result<SocketAddr> {
347 self.target
348 .to_socket_addrs()
349 .map_err(|e| {
350 Error::Config(format!("could not resolve address '{}': {}", self.target, e).into())
351 .boxed()
352 })?
353 .next()
354 .ok_or_else(|| {
355 Error::Config(format!("could not resolve address '{}'", self.target).into()).boxed()
356 })
357 }
358
359 /// Build ClientConfig from the builder settings.
360 fn build_config(&self) -> ClientConfig {
361 match &self.auth {
362 Auth::Community { version, community } => {
363 let snmp_version = match version {
364 CommunityVersion::V1 => Version::V1,
365 CommunityVersion::V2c => Version::V2c,
366 };
367 ClientConfig {
368 version: snmp_version,
369 community: Bytes::copy_from_slice(community.as_bytes()),
370 timeout: self.timeout,
371 retry: self.retry.clone(),
372 max_oids_per_request: self.max_oids_per_request,
373 v3_security: None,
374 walk_mode: self.walk_mode,
375 oid_ordering: self.oid_ordering,
376 max_walk_results: self.max_walk_results,
377 max_repetitions: self.max_repetitions,
378 }
379 }
380 Auth::Usm(usm) => {
381 let mut security = UsmConfig::new(Bytes::copy_from_slice(usm.username.as_bytes()));
382
383 // Prefer master_keys over passwords if available
384 if let Some(ref master_keys) = usm.master_keys {
385 security = security.with_master_keys(master_keys.clone());
386 } else {
387 if let (Some(auth_proto), Some(auth_pass)) =
388 (usm.auth_protocol, &usm.auth_password)
389 {
390 security = security.auth(auth_proto, auth_pass.as_bytes());
391 }
392
393 if let (Some(priv_proto), Some(priv_pass)) =
394 (usm.priv_protocol, &usm.priv_password)
395 {
396 security = security.privacy(priv_proto, priv_pass.as_bytes());
397 }
398 }
399
400 ClientConfig {
401 version: Version::V3,
402 community: Bytes::new(),
403 timeout: self.timeout,
404 retry: self.retry.clone(),
405 max_oids_per_request: self.max_oids_per_request,
406 v3_security: Some(security),
407 walk_mode: self.walk_mode,
408 oid_ordering: self.oid_ordering,
409 max_walk_results: self.max_walk_results,
410 max_repetitions: self.max_repetitions,
411 }
412 }
413 }
414 }
415
416 /// Build the client with the given transport.
417 fn build_inner<T: Transport>(self, transport: T) -> Client<T> {
418 let config = self.build_config();
419
420 if let Some(cache) = self.engine_cache {
421 Client::with_engine_cache(transport, config, cache)
422 } else {
423 Client::new(transport, config)
424 }
425 }
426
427 /// Connect via UDP (default).
428 ///
429 /// Creates a new UDP socket and connects to the target address. This is the
430 /// recommended connection method for most use cases due to UDP's lower
431 /// overhead compared to TCP.
432 ///
433 /// For polling many targets, consider using a shared
434 /// [`UdpTransport`](crate::transport::UdpTransport) with [`build_with()`](Self::build_with).
435 ///
436 /// # Errors
437 ///
438 /// Returns an error if the configuration is invalid or the connection fails.
439 ///
440 /// # Example
441 ///
442 /// ```rust,no_run
443 /// use async_snmp::{Auth, ClientBuilder};
444 ///
445 /// # async fn example() -> async_snmp::Result<()> {
446 /// let client = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
447 /// .connect()
448 /// .await?;
449 /// # Ok(())
450 /// # }
451 /// ```
452 pub async fn connect(self) -> Result<Client<UdpHandle>> {
453 self.validate()?;
454 let addr = self.resolve_target()?;
455 // Match bind address to target address family for cross-platform
456 // compatibility. Dual-stack ([::]:0) only works reliably on Linux;
457 // macOS/BSD default to IPV6_V6ONLY=1 and reject IPv4 targets.
458 let bind_addr = if addr.is_ipv6() {
459 "[::]:0"
460 } else {
461 "0.0.0.0:0"
462 };
463 let transport = UdpTransport::bind(bind_addr).await?;
464 let handle = transport.handle(addr);
465 Ok(self.build_inner(handle))
466 }
467
468 /// Build a client using a shared UDP transport.
469 ///
470 /// Creates a handle for the builder's target address from the given transport.
471 /// This is the recommended way to create multiple clients that share a socket.
472 ///
473 /// # Example
474 ///
475 /// ```rust,no_run
476 /// use async_snmp::{Auth, ClientBuilder};
477 /// use async_snmp::transport::UdpTransport;
478 ///
479 /// # async fn example() -> async_snmp::Result<()> {
480 /// let transport = UdpTransport::bind("0.0.0.0:0").await?;
481 ///
482 /// let client1 = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
483 /// .build_with(&transport)?;
484 /// let client2 = ClientBuilder::new("192.168.1.2:161", Auth::v2c("public"))
485 /// .build_with(&transport)?;
486 /// # Ok(())
487 /// # }
488 /// ```
489 pub fn build_with(self, transport: &UdpTransport) -> Result<Client<UdpHandle>> {
490 self.validate()?;
491 let addr = self.resolve_target()?;
492 let handle = transport.handle(addr);
493 Ok(self.build_inner(handle))
494 }
495
496 /// Connect via TCP.
497 ///
498 /// Establishes a TCP connection to the target. Use this when:
499 /// - UDP is blocked by firewalls
500 /// - Messages exceed UDP's maximum datagram size
501 /// - Reliable delivery is required
502 ///
503 /// Note that TCP has higher overhead than UDP due to connection setup
504 /// and per-message framing.
505 ///
506 /// For advanced TCP configuration (connection timeout, keepalive, buffer
507 /// sizes), construct a [`TcpTransport`] directly and use [`Client::new()`].
508 ///
509 /// # Errors
510 ///
511 /// Returns an error if the configuration is invalid or the connection fails.
512 ///
513 /// # Example
514 ///
515 /// ```rust,no_run
516 /// use async_snmp::{Auth, ClientBuilder};
517 ///
518 /// # async fn example() -> async_snmp::Result<()> {
519 /// let client = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
520 /// .connect_tcp()
521 /// .await?;
522 /// # Ok(())
523 /// # }
524 /// ```
525 pub async fn connect_tcp(self) -> Result<Client<TcpTransport>> {
526 self.validate()?;
527 let addr = self.resolve_target()?;
528 let transport = TcpTransport::connect(addr).await?;
529 Ok(self.build_inner(transport))
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use crate::v3::{AuthProtocol, MasterKeys, PrivProtocol};
537
538 #[test]
539 fn test_builder_defaults() {
540 let builder = ClientBuilder::new("192.168.1.1:161", Auth::default());
541 assert_eq!(builder.target, "192.168.1.1:161");
542 assert_eq!(builder.timeout, DEFAULT_TIMEOUT);
543 assert_eq!(builder.retry.max_attempts, 3);
544 assert_eq!(builder.max_oids_per_request, DEFAULT_MAX_OIDS_PER_REQUEST);
545 assert_eq!(builder.max_repetitions, DEFAULT_MAX_REPETITIONS);
546 assert_eq!(builder.walk_mode, WalkMode::Auto);
547 assert_eq!(builder.oid_ordering, OidOrdering::Strict);
548 assert!(builder.max_walk_results.is_none());
549 assert!(builder.engine_cache.is_none());
550 }
551
552 #[test]
553 fn test_builder_with_options() {
554 let cache = Arc::new(EngineCache::new());
555 let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("private"))
556 .timeout(Duration::from_secs(10))
557 .retry(Retry::fixed(5, Duration::ZERO))
558 .max_oids_per_request(20)
559 .max_repetitions(50)
560 .walk_mode(WalkMode::GetNext)
561 .oid_ordering(OidOrdering::AllowNonIncreasing)
562 .max_walk_results(1000)
563 .engine_cache(cache.clone());
564
565 assert_eq!(builder.timeout, Duration::from_secs(10));
566 assert_eq!(builder.retry.max_attempts, 5);
567 assert_eq!(builder.max_oids_per_request, 20);
568 assert_eq!(builder.max_repetitions, 50);
569 assert_eq!(builder.walk_mode, WalkMode::GetNext);
570 assert_eq!(builder.oid_ordering, OidOrdering::AllowNonIncreasing);
571 assert_eq!(builder.max_walk_results, Some(1000));
572 assert!(builder.engine_cache.is_some());
573 }
574
575 #[test]
576 fn test_validate_community_ok() {
577 let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"));
578 assert!(builder.validate().is_ok());
579 }
580
581 #[test]
582 fn test_validate_usm_no_auth_no_priv_ok() {
583 let builder = ClientBuilder::new("192.168.1.1:161", Auth::usm("readonly"));
584 assert!(builder.validate().is_ok());
585 }
586
587 #[test]
588 fn test_validate_usm_auth_no_priv_ok() {
589 let builder = ClientBuilder::new(
590 "192.168.1.1:161",
591 Auth::usm("admin").auth(AuthProtocol::Sha256, "authpass"),
592 );
593 assert!(builder.validate().is_ok());
594 }
595
596 #[test]
597 fn test_validate_usm_auth_priv_ok() {
598 let builder = ClientBuilder::new(
599 "192.168.1.1:161",
600 Auth::usm("admin")
601 .auth(AuthProtocol::Sha256, "authpass")
602 .privacy(PrivProtocol::Aes128, "privpass"),
603 );
604 assert!(builder.validate().is_ok());
605 }
606
607 #[test]
608 fn test_validate_priv_without_auth_error() {
609 // Manually construct UsmAuth with priv but no auth
610 let usm = crate::client::UsmAuth {
611 username: "user".to_string(),
612 auth_protocol: None,
613 auth_password: None,
614 priv_protocol: Some(PrivProtocol::Aes128),
615 priv_password: Some("privpass".to_string()),
616 context_name: None,
617 master_keys: None,
618 };
619 let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
620 let err = builder.validate().unwrap_err();
621 assert!(
622 matches!(*err, Error::Config(ref msg) if msg.contains("privacy requires authentication"))
623 );
624 }
625
626 #[test]
627 fn test_validate_auth_protocol_without_password_error() {
628 // Manually construct UsmAuth with auth protocol but no password
629 let usm = crate::client::UsmAuth {
630 username: "user".to_string(),
631 auth_protocol: Some(AuthProtocol::Sha256),
632 auth_password: None,
633 priv_protocol: None,
634 priv_password: None,
635 context_name: None,
636 master_keys: None,
637 };
638 let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
639 let err = builder.validate().unwrap_err();
640 assert!(
641 matches!(*err, Error::Config(ref msg) if msg.contains("auth protocol requires password"))
642 );
643 }
644
645 #[test]
646 fn test_validate_priv_protocol_without_password_error() {
647 // Manually construct UsmAuth with priv protocol but no password
648 let usm = crate::client::UsmAuth {
649 username: "user".to_string(),
650 auth_protocol: Some(AuthProtocol::Sha256),
651 auth_password: Some("authpass".to_string()),
652 priv_protocol: Some(PrivProtocol::Aes128),
653 priv_password: None,
654 context_name: None,
655 master_keys: None,
656 };
657 let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
658 let err = builder.validate().unwrap_err();
659 assert!(
660 matches!(*err, Error::Config(ref msg) if msg.contains("priv protocol requires password"))
661 );
662 }
663
664 #[test]
665 fn test_builder_with_usm_builder() {
666 // Test that UsmBuilder can be passed directly (via Into<Auth>)
667 let builder = ClientBuilder::new(
668 "192.168.1.1:161",
669 Auth::usm("admin").auth(AuthProtocol::Sha256, "pass"),
670 );
671 assert!(builder.validate().is_ok());
672 }
673
674 #[test]
675 fn test_validate_master_keys_bypass_auth_password() {
676 // When master keys are set, auth password is not required
677 let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpass");
678 let usm = crate::client::UsmAuth {
679 username: "user".to_string(),
680 auth_protocol: Some(AuthProtocol::Sha256),
681 auth_password: None, // No password
682 priv_protocol: None,
683 priv_password: None,
684 context_name: None,
685 master_keys: Some(master_keys),
686 };
687 let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
688 assert!(builder.validate().is_ok());
689 }
690
691 #[test]
692 fn test_validate_master_keys_bypass_priv_password() {
693 // When master keys are set, priv password is not required
694 let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpass")
695 .with_privacy(PrivProtocol::Aes128, b"privpass");
696 let usm = crate::client::UsmAuth {
697 username: "user".to_string(),
698 auth_protocol: Some(AuthProtocol::Sha256),
699 auth_password: None, // No password
700 priv_protocol: Some(PrivProtocol::Aes128),
701 priv_password: None, // No password
702 context_name: None,
703 master_keys: Some(master_keys),
704 };
705 let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
706 assert!(builder.validate().is_ok());
707 }
708}