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        // Use dual-stack socket for both IPv4 and IPv6 targets
456        let transport = UdpTransport::bind("[::]:0").await?;
457        let handle = transport.handle(addr);
458        Ok(self.build_inner(handle))
459    }
460
461    /// Build a client using a shared UDP transport.
462    ///
463    /// Creates a handle for the builder's target address from the given transport.
464    /// This is the recommended way to create multiple clients that share a socket.
465    ///
466    /// # Example
467    ///
468    /// ```rust,no_run
469    /// use async_snmp::{Auth, ClientBuilder};
470    /// use async_snmp::transport::UdpTransport;
471    ///
472    /// # async fn example() -> async_snmp::Result<()> {
473    /// let transport = UdpTransport::bind("0.0.0.0:0").await?;
474    ///
475    /// let client1 = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
476    ///     .build_with(&transport)?;
477    /// let client2 = ClientBuilder::new("192.168.1.2:161", Auth::v2c("public"))
478    ///     .build_with(&transport)?;
479    /// # Ok(())
480    /// # }
481    /// ```
482    pub fn build_with(self, transport: &UdpTransport) -> Result<Client<UdpHandle>> {
483        self.validate()?;
484        let addr = self.resolve_target()?;
485        let handle = transport.handle(addr);
486        Ok(self.build_inner(handle))
487    }
488
489    /// Connect via TCP.
490    ///
491    /// Establishes a TCP connection to the target. Use this when:
492    /// - UDP is blocked by firewalls
493    /// - Messages exceed UDP's maximum datagram size
494    /// - Reliable delivery is required
495    ///
496    /// Note that TCP has higher overhead than UDP due to connection setup
497    /// and per-message framing.
498    ///
499    /// For advanced TCP configuration (connection timeout, keepalive, buffer
500    /// sizes), construct a [`TcpTransport`] directly and use [`Client::new()`].
501    ///
502    /// # Errors
503    ///
504    /// Returns an error if the configuration is invalid or the connection fails.
505    ///
506    /// # Example
507    ///
508    /// ```rust,no_run
509    /// use async_snmp::{Auth, ClientBuilder};
510    ///
511    /// # async fn example() -> async_snmp::Result<()> {
512    /// let client = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"))
513    ///     .connect_tcp()
514    ///     .await?;
515    /// # Ok(())
516    /// # }
517    /// ```
518    pub async fn connect_tcp(self) -> Result<Client<TcpTransport>> {
519        self.validate()?;
520        let addr = self.resolve_target()?;
521        let transport = TcpTransport::connect(addr).await?;
522        Ok(self.build_inner(transport))
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use crate::v3::{AuthProtocol, MasterKeys, PrivProtocol};
530
531    #[test]
532    fn test_builder_defaults() {
533        let builder = ClientBuilder::new("192.168.1.1:161", Auth::default());
534        assert_eq!(builder.target, "192.168.1.1:161");
535        assert_eq!(builder.timeout, DEFAULT_TIMEOUT);
536        assert_eq!(builder.retry.max_attempts, 3);
537        assert_eq!(builder.max_oids_per_request, DEFAULT_MAX_OIDS_PER_REQUEST);
538        assert_eq!(builder.max_repetitions, DEFAULT_MAX_REPETITIONS);
539        assert_eq!(builder.walk_mode, WalkMode::Auto);
540        assert_eq!(builder.oid_ordering, OidOrdering::Strict);
541        assert!(builder.max_walk_results.is_none());
542        assert!(builder.engine_cache.is_none());
543    }
544
545    #[test]
546    fn test_builder_with_options() {
547        let cache = Arc::new(EngineCache::new());
548        let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("private"))
549            .timeout(Duration::from_secs(10))
550            .retry(Retry::fixed(5, Duration::ZERO))
551            .max_oids_per_request(20)
552            .max_repetitions(50)
553            .walk_mode(WalkMode::GetNext)
554            .oid_ordering(OidOrdering::AllowNonIncreasing)
555            .max_walk_results(1000)
556            .engine_cache(cache.clone());
557
558        assert_eq!(builder.timeout, Duration::from_secs(10));
559        assert_eq!(builder.retry.max_attempts, 5);
560        assert_eq!(builder.max_oids_per_request, 20);
561        assert_eq!(builder.max_repetitions, 50);
562        assert_eq!(builder.walk_mode, WalkMode::GetNext);
563        assert_eq!(builder.oid_ordering, OidOrdering::AllowNonIncreasing);
564        assert_eq!(builder.max_walk_results, Some(1000));
565        assert!(builder.engine_cache.is_some());
566    }
567
568    #[test]
569    fn test_validate_community_ok() {
570        let builder = ClientBuilder::new("192.168.1.1:161", Auth::v2c("public"));
571        assert!(builder.validate().is_ok());
572    }
573
574    #[test]
575    fn test_validate_usm_no_auth_no_priv_ok() {
576        let builder = ClientBuilder::new("192.168.1.1:161", Auth::usm("readonly"));
577        assert!(builder.validate().is_ok());
578    }
579
580    #[test]
581    fn test_validate_usm_auth_no_priv_ok() {
582        let builder = ClientBuilder::new(
583            "192.168.1.1:161",
584            Auth::usm("admin").auth(AuthProtocol::Sha256, "authpass"),
585        );
586        assert!(builder.validate().is_ok());
587    }
588
589    #[test]
590    fn test_validate_usm_auth_priv_ok() {
591        let builder = ClientBuilder::new(
592            "192.168.1.1:161",
593            Auth::usm("admin")
594                .auth(AuthProtocol::Sha256, "authpass")
595                .privacy(PrivProtocol::Aes128, "privpass"),
596        );
597        assert!(builder.validate().is_ok());
598    }
599
600    #[test]
601    fn test_validate_priv_without_auth_error() {
602        // Manually construct UsmAuth with priv but no auth
603        let usm = crate::client::UsmAuth {
604            username: "user".to_string(),
605            auth_protocol: None,
606            auth_password: None,
607            priv_protocol: Some(PrivProtocol::Aes128),
608            priv_password: Some("privpass".to_string()),
609            context_name: None,
610            master_keys: None,
611        };
612        let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
613        let err = builder.validate().unwrap_err();
614        assert!(
615            matches!(*err, Error::Config(ref msg) if msg.contains("privacy requires authentication"))
616        );
617    }
618
619    #[test]
620    fn test_validate_auth_protocol_without_password_error() {
621        // Manually construct UsmAuth with auth protocol but no password
622        let usm = crate::client::UsmAuth {
623            username: "user".to_string(),
624            auth_protocol: Some(AuthProtocol::Sha256),
625            auth_password: None,
626            priv_protocol: None,
627            priv_password: None,
628            context_name: None,
629            master_keys: None,
630        };
631        let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
632        let err = builder.validate().unwrap_err();
633        assert!(
634            matches!(*err, Error::Config(ref msg) if msg.contains("auth protocol requires password"))
635        );
636    }
637
638    #[test]
639    fn test_validate_priv_protocol_without_password_error() {
640        // Manually construct UsmAuth with priv protocol but no password
641        let usm = crate::client::UsmAuth {
642            username: "user".to_string(),
643            auth_protocol: Some(AuthProtocol::Sha256),
644            auth_password: Some("authpass".to_string()),
645            priv_protocol: Some(PrivProtocol::Aes128),
646            priv_password: None,
647            context_name: None,
648            master_keys: None,
649        };
650        let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
651        let err = builder.validate().unwrap_err();
652        assert!(
653            matches!(*err, Error::Config(ref msg) if msg.contains("priv protocol requires password"))
654        );
655    }
656
657    #[test]
658    fn test_builder_with_usm_builder() {
659        // Test that UsmBuilder can be passed directly (via Into<Auth>)
660        let builder = ClientBuilder::new(
661            "192.168.1.1:161",
662            Auth::usm("admin").auth(AuthProtocol::Sha256, "pass"),
663        );
664        assert!(builder.validate().is_ok());
665    }
666
667    #[test]
668    fn test_validate_master_keys_bypass_auth_password() {
669        // When master keys are set, auth password is not required
670        let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpass");
671        let usm = crate::client::UsmAuth {
672            username: "user".to_string(),
673            auth_protocol: Some(AuthProtocol::Sha256),
674            auth_password: None, // No password
675            priv_protocol: None,
676            priv_password: None,
677            context_name: None,
678            master_keys: Some(master_keys),
679        };
680        let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
681        assert!(builder.validate().is_ok());
682    }
683
684    #[test]
685    fn test_validate_master_keys_bypass_priv_password() {
686        // When master keys are set, priv password is not required
687        let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpass")
688            .with_privacy(PrivProtocol::Aes128, b"privpass");
689        let usm = crate::client::UsmAuth {
690            username: "user".to_string(),
691            auth_protocol: Some(AuthProtocol::Sha256),
692            auth_password: None, // No password
693            priv_protocol: Some(PrivProtocol::Aes128),
694            priv_password: None, // No password
695            context_name: None,
696            master_keys: Some(master_keys),
697        };
698        let builder = ClientBuilder::new("192.168.1.1:161", Auth::Usm(usm));
699        assert!(builder.validate().is_ok());
700    }
701}