async-snmp 0.18.1

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
//! USM configuration types for `SNMPv3` authentication.
//!
//! [`UsmConfig`] selects the exact credentials and context used for outbound
//! messages. [`UsmUser`] describes the mechanisms an inbound user supports.

use bytes::Bytes;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::message::SecurityLevel;
use crate::v3::{
    AuthProtocol, CryptoBackend, CryptoError, CryptoResult, LocalizedKey, PrivKey, PrivProtocol,
};

#[derive(Clone, Zeroize, ZeroizeOnDrop)]
struct Password(Vec<u8>);

impl AsRef<[u8]> for Password {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

#[derive(Clone)]
enum UsmCredentials {
    NoAuthNoPriv,
    Passwords {
        auth: (AuthProtocol, Password),
        privacy: Option<(PrivProtocol, Password)>,
    },
    MasterKeys(crate::v3::MasterKeys),
}

/// USM user credentials for `SNMPv3` authentication.
///
/// A configuration represents exactly one valid USM security state:
/// noAuthNoPriv, password-backed authNoPriv/authPriv, or master-key-backed
/// authNoPriv/authPriv. Privacy-only and incomplete protocol/password states
/// cannot be constructed.
///
/// # Password storage
///
/// Password-backed configurations zeroize the specifically owned password
/// buffers when those buffers are dropped. This guarantee does not extend to
/// caller-provided inputs, live clones, allocator or cryptographic-provider
/// internals, encoded message buffers, or kernel copies.
#[derive(Clone)]
pub struct UsmConfig {
    username: Bytes,
    credentials: UsmCredentials,
    context_name: Bytes,
    crypto_backend: CryptoBackend,
    crypto_backend_explicit: bool,
}

/// USM user accepted by an inbound `SNMPv3` application.
///
/// Authentication and privacy protocols are capabilities, not a minimum
/// accepted security level. A user with authentication and privacy keys also
/// supports `authNoPriv` and `noAuthNoPriv`; the Agent or notification receiver
/// applies its own authorization or acceptance policy to the packet's actual
/// security level.
///
/// Unlike [`UsmConfig`], this type has no scoped-PDU context because inbound
/// contexts come from the received message.
#[derive(Clone)]
pub struct UsmUser {
    config: UsmConfig,
}

impl UsmUser {
    /// Create an inbound user supporting `noAuthNoPriv` only.
    pub fn new(username: impl Into<Bytes>) -> Self {
        Self {
            config: UsmConfig::new(username),
        }
    }

    /// Add password-backed authentication capability.
    pub fn auth(
        mut self,
        protocol: AuthProtocol,
        password: impl AsRef<[u8]>,
    ) -> CryptoResult<Self> {
        self.config = self.config.auth(protocol, password)?;
        Ok(self)
    }

    /// Add password-backed authentication and privacy capability.
    pub fn auth_priv(
        mut self,
        auth_protocol: AuthProtocol,
        auth_password: impl AsRef<[u8]>,
        priv_protocol: PrivProtocol,
        priv_password: impl AsRef<[u8]>,
    ) -> CryptoResult<Self> {
        self.config =
            self.config
                .auth_priv(auth_protocol, auth_password, priv_protocol, priv_password)?;
        Ok(self)
    }

    /// Select the cryptographic backend for this inbound user.
    pub fn with_crypto_backend(mut self, backend: CryptoBackend) -> CryptoResult<Self> {
        self.config = self.config.with_crypto_backend(backend)?;
        Ok(self)
    }

    /// Return the selected cryptographic backend.
    #[must_use]
    pub fn crypto_backend(&self) -> Option<CryptoBackend> {
        self.config.crypto_backend()
    }

    /// Use pre-computed master keys for this inbound user.
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    pub fn with_master_keys(mut self, master_keys: crate::v3::MasterKeys) -> CryptoResult<Self> {
        self.config = self.config.with_master_keys(master_keys)?;
        Ok(self)
    }

    /// Return the configured username.
    #[must_use]
    pub fn username(&self) -> &Bytes {
        self.config.username()
    }

    /// Return the configured authentication protocol, if any.
    #[must_use]
    pub fn auth_protocol(&self) -> Option<AuthProtocol> {
        self.config.auth_protocol()
    }

    /// Return the configured privacy protocol, if any.
    #[must_use]
    pub fn priv_protocol(&self) -> Option<PrivProtocol> {
        self.config.priv_protocol()
    }

    /// Return the strongest security level supported by this user.
    ///
    /// This is a capability, not a minimum accepted level.
    #[must_use]
    pub fn maximum_security_level(&self) -> SecurityLevel {
        self.config.security_level()
    }

    pub(crate) fn validate_and_precompute(&mut self) -> CryptoResult<()> {
        self.config.validate_and_precompute()
    }

    pub(crate) fn derive_keys(&self, engine_id: &[u8]) -> CryptoResult<DerivedKeys> {
        self.config.derive_keys_inner(engine_id)
    }
}

impl std::fmt::Debug for UsmUser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UsmUser")
            .field("username", self.username())
            .field("auth_protocol", &self.auth_protocol())
            .field("priv_protocol", &self.priv_protocol())
            .field("maximum_security_level", &self.maximum_security_level())
            .field("crypto_backend", &self.config.crypto_backend)
            .finish()
    }
}

impl UsmConfig {
    /// Create a noAuthNoPriv USM config with the given username.
    pub fn new(username: impl Into<Bytes>) -> Self {
        Self {
            username: username.into(),
            credentials: UsmCredentials::NoAuthNoPriv,
            context_name: Bytes::new(),
            crypto_backend: CryptoBackend::default_backend().unwrap_or(CryptoBackend::RustCrypto),
            crypto_backend_explicit: false,
        }
    }

    /// Configure password-backed authentication (authNoPriv).
    ///
    /// Returns an error immediately when no backend is compiled, the selected
    /// backend does not support `protocol`, or the password is too short.
    pub fn auth(
        mut self,
        protocol: AuthProtocol,
        password: impl AsRef<[u8]>,
    ) -> CryptoResult<Self> {
        self.credentials = UsmCredentials::Passwords {
            auth: (protocol, Password(password.as_ref().to_vec())),
            privacy: None,
        };
        self.validate_credential_capabilities()?;
        Ok(self)
    }

    /// Configure password-backed authentication and privacy (authPriv).
    ///
    /// Returns an error immediately when no backend is compiled, the selected
    /// backend does not support either protocol, or either password is too
    /// short.
    pub fn auth_priv(
        mut self,
        auth_protocol: AuthProtocol,
        auth_password: impl AsRef<[u8]>,
        priv_protocol: PrivProtocol,
        priv_password: impl AsRef<[u8]>,
    ) -> CryptoResult<Self> {
        self.credentials = UsmCredentials::Passwords {
            auth: (auth_protocol, Password(auth_password.as_ref().to_vec())),
            privacy: Some((priv_protocol, Password(priv_password.as_ref().to_vec()))),
        };
        self.validate_credential_capabilities()?;
        Ok(self)
    }

    /// Select the cryptographic backend for this USM configuration.
    ///
    /// When both backend features are enabled the default remains RustCrypto;
    /// select `AwsLcFips` explicitly for FIPS operations.
    pub fn with_crypto_backend(mut self, backend: CryptoBackend) -> CryptoResult<Self> {
        if !backend.is_compiled() {
            return Err(CryptoError::BackendNotCompiled(backend));
        }
        self.crypto_backend = backend;
        self.crypto_backend_explicit = true;
        self.validate_credential_capabilities()?;
        if let UsmCredentials::MasterKeys(master_keys) = &mut self.credentials {
            master_keys.set_crypto_backend(backend);
        }
        Ok(self)
    }

    /// Return the selected cryptographic backend.
    #[must_use]
    pub fn crypto_backend(&self) -> Option<CryptoBackend> {
        self.crypto_backend
            .is_compiled()
            .then_some(self.crypto_backend)
    }

    /// Set the `SNMPv3` context name for scoped PDUs.
    #[must_use]
    pub fn context_name(mut self, context_name: impl Into<Bytes>) -> Self {
        self.context_name = context_name.into();
        self
    }

    /// Use pre-computed master keys.
    ///
    /// # Reusing master keys
    ///
    /// When polling many engines with shared credentials, use
    /// [`MasterKeys`](crate::MasterKeys) to avoid repeating password-to-key
    /// derivation. Calling this method replaces any password-backed credentials
    /// with the supplied master keys. Credential configurators use
    /// last-call-wins semantics.
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    pub fn with_master_keys(
        mut self,
        mut master_keys: crate::v3::MasterKeys,
    ) -> CryptoResult<Self> {
        self.crypto_backend
            .validate_auth_protocol(master_keys.auth_protocol())?;
        if let Some(protocol) = master_keys.priv_protocol() {
            self.crypto_backend.validate_priv_protocol(protocol)?;
        }
        master_keys.set_crypto_backend(self.crypto_backend);
        self.credentials = UsmCredentials::MasterKeys(master_keys);
        Ok(self)
    }

    /// Return the configured USM username.
    #[must_use]
    pub fn username(&self) -> &Bytes {
        &self.username
    }

    /// Return the configured scoped-PDU context name.
    #[must_use]
    pub fn configured_context_name(&self) -> &Bytes {
        &self.context_name
    }

    /// Return the configured authentication protocol, if any.
    #[must_use]
    pub fn auth_protocol(&self) -> Option<AuthProtocol> {
        match &self.credentials {
            UsmCredentials::NoAuthNoPriv => None,
            UsmCredentials::Passwords { auth, .. } => Some(auth.0),
            UsmCredentials::MasterKeys(master_keys) => Some(master_keys.auth_protocol()),
        }
    }

    /// Return the configured privacy protocol, if any.
    #[must_use]
    pub fn priv_protocol(&self) -> Option<PrivProtocol> {
        match &self.credentials {
            UsmCredentials::NoAuthNoPriv | UsmCredentials::Passwords { privacy: None, .. } => None,
            UsmCredentials::Passwords {
                privacy: Some((protocol, _)),
                ..
            } => Some(*protocol),
            UsmCredentials::MasterKeys(master_keys) => master_keys.priv_protocol(),
        }
    }

    /// Returns the configured security level.
    #[must_use]
    pub fn security_level(&self) -> SecurityLevel {
        match &self.credentials {
            UsmCredentials::NoAuthNoPriv => SecurityLevel::NoAuthNoPriv,
            UsmCredentials::Passwords { privacy: None, .. } => SecurityLevel::AuthNoPriv,
            UsmCredentials::Passwords {
                privacy: Some(_), ..
            } => SecurityLevel::AuthPriv,
            UsmCredentials::MasterKeys(master_keys) if master_keys.priv_protocol().is_some() => {
                SecurityLevel::AuthPriv
            }
            UsmCredentials::MasterKeys(_) => SecurityLevel::AuthNoPriv,
        }
    }

    fn validate_credential_capabilities(&self) -> CryptoResult<()> {
        match &self.credentials {
            UsmCredentials::NoAuthNoPriv => Ok(()),
            UsmCredentials::MasterKeys(master_keys) => {
                if !self.crypto_backend_explicit && CryptoBackend::default_backend().is_none() {
                    return Err(CryptoError::BackendUnavailable);
                }
                self.crypto_backend
                    .validate_auth_protocol(master_keys.auth_protocol())?;
                if let Some(protocol) = master_keys.priv_protocol() {
                    self.crypto_backend.validate_priv_protocol(protocol)?;
                }
                Ok(())
            }
            UsmCredentials::Passwords { auth, privacy } => {
                if auth.1.as_ref().len() < crate::v3::auth::MIN_PASSWORD_LENGTH
                    || privacy.as_ref().is_some_and(|(_, password)| {
                        password.as_ref().len() < crate::v3::auth::MIN_PASSWORD_LENGTH
                    })
                {
                    return Err(CryptoError::PasswordTooShort);
                }
                if !self.crypto_backend_explicit && CryptoBackend::default_backend().is_none() {
                    return Err(CryptoError::BackendUnavailable);
                }
                self.crypto_backend.validate_auth_protocol(auth.0)?;
                if let Some((protocol, _)) = privacy {
                    self.crypto_backend.validate_priv_protocol(*protocol)?;
                }
                Ok(())
            }
        }
    }

    /// Validate credentials and precompute password-backed master keys.
    ///
    /// Validation uses raw octet lengths and the selected cryptographic backend.
    /// Password-backed credentials are replaced only after all requested key
    /// derivations succeed, so an error never leaves partially updated state.
    pub(crate) fn validate_and_precompute(&mut self) -> CryptoResult<()> {
        if !(1..=32).contains(&self.username.len()) {
            return Err(CryptoError::InvalidUsmUsernameLength {
                length: self.username.len(),
            });
        }

        self.validate_credential_capabilities()?;

        match &self.credentials {
            UsmCredentials::NoAuthNoPriv | UsmCredentials::MasterKeys(_) => Ok(()),
            UsmCredentials::Passwords { auth, privacy } => {
                let (auth_protocol, auth_password) = auth;
                let master_keys = crate::v3::MasterKeys::new_with_backend(
                    *auth_protocol,
                    auth_password.as_ref(),
                    self.crypto_backend,
                )?;
                let master_keys = match privacy {
                    Some((priv_protocol, priv_password)) => {
                        master_keys.with_privacy(*priv_protocol, priv_password.as_ref())?
                    }
                    None => master_keys,
                };
                self.credentials = UsmCredentials::MasterKeys(master_keys);
                Ok(())
            }
        }
    }

    /// Derive the localized keys used for one authoritative engine.
    ///
    /// A `noAuthNoPriv` configuration returns empty key slots. Credentialed
    /// configurations return a capability error when their selected backend is
    /// unavailable.
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    pub fn derive_keys(&self, engine_id: &[u8]) -> crate::v3::CryptoResult<DerivedKeys> {
        self.derive_keys_inner(engine_id)
    }

    pub(crate) fn derive_keys_inner(
        &self,
        engine_id: &[u8],
    ) -> crate::v3::CryptoResult<DerivedKeys> {
        match &self.credentials {
            UsmCredentials::NoAuthNoPriv => Ok(DerivedKeys {
                auth_key: None,
                priv_key: None,
            }),
            UsmCredentials::MasterKeys(master_keys) => {
                tracing::trace!(target: "async_snmp::client", { engine_id_len = engine_id.len(), auth_protocol = ?master_keys.auth_protocol(), priv_protocol = ?master_keys.priv_protocol() }, "localizing from cached master keys");
                let (auth_key, priv_key) = master_keys.localize(engine_id)?;
                Ok(DerivedKeys {
                    auth_key: Some(auth_key),
                    priv_key,
                })
            }
            UsmCredentials::Passwords { auth, privacy } => {
                let (auth_protocol, auth_password) = auth;
                tracing::trace!(target: "async_snmp::client", { engine_id_len = engine_id.len(), auth_protocol = ?auth_protocol }, "deriving localized keys from passwords");
                let auth_key = LocalizedKey::from_password_with_backend(
                    *auth_protocol,
                    auth_password.as_ref(),
                    engine_id,
                    self.crypto_backend,
                )?;
                let priv_key = privacy
                    .as_ref()
                    .map(|(priv_protocol, priv_password)| {
                        PrivKey::from_password_with_backend(
                            *auth_protocol,
                            *priv_protocol,
                            priv_password.as_ref(),
                            engine_id,
                            self.crypto_backend,
                        )
                    })
                    .transpose()?;
                Ok(DerivedKeys {
                    auth_key: Some(auth_key),
                    priv_key,
                })
            }
        }
    }
}

impl std::fmt::Debug for UsmConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (auth, auth_password, privacy, priv_password, master_keys) = match &self.credentials {
            UsmCredentials::NoAuthNoPriv => (None, None, None, None, None),
            UsmCredentials::Passwords { auth, privacy } => (
                Some(auth.0),
                Some("[REDACTED]"),
                privacy.as_ref().map(|value| value.0),
                privacy.as_ref().map(|_| "[REDACTED]"),
                None,
            ),
            UsmCredentials::MasterKeys(master_keys) => (
                Some(master_keys.auth_protocol()),
                None,
                master_keys.priv_protocol(),
                None,
                Some("[REDACTED]"),
            ),
        };
        f.debug_struct("UsmConfig")
            .field("username", &self.username)
            .field("auth_protocol", &auth)
            .field("auth_password", &auth_password)
            .field("priv_protocol", &privacy)
            .field("priv_password", &priv_password)
            .field("context_name", &self.context_name)
            .field("crypto_backend", &self.crypto_backend)
            .field("master_keys", &master_keys)
            .finish()
    }
}

/// Derived keys for a specific engine ID.
///
/// Localized authentication and privacy keys for one authoritative engine.
///
/// Applications may derive and reuse this public value through
/// [`UsmConfig::derive_keys`]. The key wrapper types redact their material from
/// diagnostics and zeroize owned key bytes when dropped.
#[derive(Debug)]
pub struct DerivedKeys {
    /// Localized authentication key
    pub auth_key: Option<LocalizedKey>,
    /// Privacy key
    pub priv_key: Option<PrivKey>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use static_assertions::assert_not_impl_any;

    assert_not_impl_any!(Password: PartialEq, Eq, PartialOrd, Ord, std::hash::Hash);
    assert_not_impl_any!(UsmCredentials: PartialEq, Eq, PartialOrd, Ord, std::hash::Hash);

    #[test]
    fn test_usm_user_config_no_auth() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser"));
        assert_eq!(config.security_level(), SecurityLevel::NoAuthNoPriv);
        assert_eq!(config.auth_protocol(), None);
        assert_eq!(config.priv_protocol(), None);
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_usm_user_config_auth_only() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser"))
            .auth(AuthProtocol::Sha1, b"password123")
            .unwrap();
        assert_eq!(config.security_level(), SecurityLevel::AuthNoPriv);
        assert_eq!(config.auth_protocol(), Some(AuthProtocol::Sha1));
        assert_eq!(config.priv_protocol(), None);
        assert!(config.configured_context_name().is_empty());
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_usm_user_config_auth_priv() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser"))
            .auth_priv(
                AuthProtocol::Sha256,
                b"authpass",
                PrivProtocol::Aes128,
                b"privpass",
            )
            .unwrap();
        assert_eq!(config.security_level(), SecurityLevel::AuthPriv);
        assert_eq!(config.auth_protocol(), Some(AuthProtocol::Sha256));
        assert_eq!(config.priv_protocol(), Some(PrivProtocol::Aes128));
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_usm_user_config_master_key_levels() {
        let auth = crate::v3::MasterKeys::new(AuthProtocol::Sha256, b"authpass").unwrap();
        let auth_config = UsmConfig::new("user").with_master_keys(auth).unwrap();
        assert_eq!(auth_config.security_level(), SecurityLevel::AuthNoPriv);
        assert_eq!(auth_config.auth_protocol(), Some(AuthProtocol::Sha256));
        assert_eq!(auth_config.priv_protocol(), None);

        let auth_priv = crate::v3::MasterKeys::new(AuthProtocol::Sha256, b"authpass")
            .unwrap()
            .with_privacy(PrivProtocol::Aes128, b"privpass")
            .unwrap();
        let auth_priv_config = UsmConfig::new("user").with_master_keys(auth_priv).unwrap();
        assert_eq!(auth_priv_config.security_level(), SecurityLevel::AuthPriv);
        assert_eq!(auth_priv_config.auth_protocol(), Some(AuthProtocol::Sha256));
        assert_eq!(auth_priv_config.priv_protocol(), Some(PrivProtocol::Aes128));
        let keys = auth_priv_config.derive_keys(b"test-engine-id").unwrap();
        assert!(keys.auth_key.is_some());
        assert!(keys.priv_key.is_some());
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_password_configurators_replace_master_keys() {
        let master_keys = crate::v3::MasterKeys::new(AuthProtocol::Sha256, b"masterauthpass")
            .unwrap()
            .with_privacy(PrivProtocol::Aes128, b"masterprivpass")
            .unwrap();
        let auth_config = UsmConfig::new("user")
            .with_master_keys(master_keys.clone())
            .unwrap()
            .auth(AuthProtocol::Sha1, b"passwordauth")
            .unwrap();

        assert_eq!(auth_config.security_level(), SecurityLevel::AuthNoPriv);
        assert_eq!(auth_config.auth_protocol(), Some(AuthProtocol::Sha1));
        assert_eq!(auth_config.priv_protocol(), None);

        let auth_priv_config = UsmConfig::new("user")
            .with_master_keys(master_keys)
            .unwrap()
            .auth_priv(
                AuthProtocol::Sha512,
                b"otherauthpass",
                PrivProtocol::Aes256Blumenthal,
                b"otherprivpass",
            )
            .unwrap();

        assert_eq!(auth_priv_config.security_level(), SecurityLevel::AuthPriv);
        assert_eq!(auth_priv_config.auth_protocol(), Some(AuthProtocol::Sha512));
        assert_eq!(
            auth_priv_config.priv_protocol(),
            Some(PrivProtocol::Aes256Blumenthal)
        );
        assert!(
            auth_priv_config
                .derive_keys(b"test-engine-id")
                .unwrap()
                .priv_key
                .is_some()
        );
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_master_key_debug_redacts_key_material() {
        let master_keys = crate::v3::MasterKeys::new(AuthProtocol::Sha256, b"masterauthpass")
            .unwrap()
            .with_privacy(PrivProtocol::Aes128, b"masterprivpass")
            .unwrap();
        let rendered = format!(
            "{:?}",
            UsmConfig::new("user")
                .with_master_keys(master_keys)
                .unwrap()
        );

        assert!(rendered.contains("[REDACTED]"), "{rendered}");
        assert!(rendered.contains("auth_password: None"), "{rendered}");
        assert!(rendered.contains("priv_password: None"), "{rendered}");
        assert!(rendered.contains("master_keys: Some"), "{rendered}");
        assert!(!rendered.contains("masterauthpass"), "{rendered}");
        assert!(!rendered.contains("masterprivpass"), "{rendered}");
    }

    #[test]
    fn test_usm_user_config_context_name() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser")).context_name("ctx");
        assert_eq!(config.configured_context_name().as_ref(), b"ctx");
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_usm_user_config_derive_keys() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser"))
            .auth(AuthProtocol::Sha1, b"password123")
            .unwrap();

        let engine_id = b"test-engine-id";
        let keys = config.derive_keys(engine_id).unwrap();

        assert!(keys.auth_key.is_some());
        assert!(keys.priv_key.is_none());
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_usm_user_config_derive_keys_with_privacy() {
        let config = UsmConfig::new(Bytes::from_static(b"testuser"))
            .auth_priv(
                AuthProtocol::Sha256,
                b"authpass",
                PrivProtocol::Aes128,
                b"privpass",
            )
            .unwrap();

        let engine_id = b"test-engine-id";
        let keys = config.derive_keys(engine_id).unwrap();

        assert!(keys.auth_key.is_some());
        assert!(keys.priv_key.is_some());
    }

    /// Precomputing master keys populates the cache, so subsequent
    /// `derive_keys` calls take the master-key localization path instead of
    /// re-running the 1 MiB password expansion (the CPU-amplification vector).
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_precompute_master_keys_replaces_passwords() {
        let mut config = UsmConfig::new(Bytes::from_static(b"testuser"))
            .auth_priv(
                AuthProtocol::Sha256,
                b"authpass",
                PrivProtocol::Aes128,
                b"privpass",
            )
            .unwrap();

        config.validate_and_precompute().unwrap();
        assert!(matches!(config.credentials, UsmCredentials::MasterKeys(_)));

        // Idempotent: a second call is a no-op and keeps the cache.
        config.validate_and_precompute().unwrap();
        assert!(matches!(config.credentials, UsmCredentials::MasterKeys(_)));
    }

    /// The cached (master-key) path and the uncached (password) path must
    /// derive identical localized keys, for both auth-only and authPriv.
    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn test_precompute_master_keys_preserves_derivation() {
        let engine_id = b"\x80\x00\x00\x00\x01test-engine";

        // authNoPriv
        let uncached = UsmConfig::new(Bytes::from_static(b"u"))
            .auth(AuthProtocol::Sha256, b"authpass")
            .unwrap();
        let mut cached = uncached.clone();
        cached.validate_and_precompute().unwrap();
        let a = uncached.derive_keys(engine_id).unwrap();
        let b = cached.derive_keys(engine_id).unwrap();
        assert_eq!(
            a.auth_key.as_ref().map(AsRef::as_ref),
            b.auth_key.as_ref().map(AsRef::as_ref),
            "auth key must match between password and master-key paths"
        );

        // authPriv, distinct auth/priv passwords
        let uncached = UsmConfig::new(Bytes::from_static(b"u"))
            .auth_priv(
                AuthProtocol::Sha1,
                b"authpassword",
                PrivProtocol::Aes128,
                b"privpassword",
            )
            .unwrap();
        let mut cached = uncached.clone();
        cached.validate_and_precompute().unwrap();
        let a = uncached.derive_keys(engine_id).unwrap();
        let b = cached.derive_keys(engine_id).unwrap();
        assert_eq!(
            a.auth_key.as_ref().map(AsRef::as_ref),
            b.auth_key.as_ref().map(AsRef::as_ref),
        );
        let a_priv = a.priv_key.as_ref().expect("password path privacy key");
        let b_priv = b.priv_key.as_ref().expect("master-key path privacy key");
        assert_eq!(a_priv.protocol(), b_priv.protocol());
        assert_eq!(a_priv.encryption_key(), b_priv.encryption_key());

        // authPriv, same auth/priv password through the general derivation path
        let uncached = UsmConfig::new(Bytes::from_static(b"u"))
            .auth_priv(
                AuthProtocol::Sha1,
                b"sharedpassword",
                PrivProtocol::Aes128,
                b"sharedpassword",
            )
            .unwrap();
        let mut cached = uncached.clone();
        cached.validate_and_precompute().unwrap();
        let a = uncached.derive_keys(engine_id).unwrap();
        let b = cached.derive_keys(engine_id).unwrap();
        assert_eq!(
            a.auth_key.as_ref().map(AsRef::as_ref),
            b.auth_key.as_ref().map(AsRef::as_ref),
        );
        let a_priv = a.priv_key.as_ref().expect("password path privacy key");
        let b_priv = b.priv_key.as_ref().expect("master-key path privacy key");
        assert_eq!(a_priv.protocol(), b_priv.protocol());
        assert_eq!(a_priv.encryption_key(), b_priv.encryption_key());
    }

    #[test]
    fn validate_username_octet_boundaries() {
        for username in [vec![0xff], vec![b'u'; 32]] {
            let mut config = UsmConfig::new(Bytes::from(username));
            assert!(config.validate_and_precompute().is_ok());
        }

        for username in [Vec::new(), vec![b'u'; 33]] {
            let expected = username.len();
            let mut config = UsmConfig::new(Bytes::from(username));
            assert_eq!(
                config.validate_and_precompute(),
                Err(CryptoError::InvalidUsmUsernameLength { length: expected })
            );
        }
    }

    #[test]
    fn credential_configuration_rejects_each_short_password() {
        assert!(matches!(
            UsmConfig::new("user").auth(AuthProtocol::Sha256, b"1234567"),
            Err(CryptoError::PasswordTooShort)
        ));
        assert!(matches!(
            UsmConfig::new("user").auth_priv(
                AuthProtocol::Sha256,
                b"12345678",
                PrivProtocol::Aes128,
                b"1234567",
            ),
            Err(CryptoError::PasswordTooShort)
        ));
    }

    #[cfg(not(any(feature = "crypto-rustcrypto", feature = "crypto-fips")))]
    #[test]
    fn password_credentials_are_rejected_without_crypto_backend() {
        assert!(matches!(
            UsmConfig::new("user").auth(AuthProtocol::Sha256, b"authpassword"),
            Err(CryptoError::BackendUnavailable)
        ));
        assert!(matches!(
            UsmUser::new("user").auth(AuthProtocol::Sha256, b"authpassword"),
            Err(CryptoError::BackendUnavailable)
        ));
    }

    #[cfg(any(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn validate_accepts_eight_octet_passwords() {
        let mut config = UsmConfig::new("user")
            .auth_priv(
                AuthProtocol::Sha256,
                b"12345678",
                PrivProtocol::Aes128,
                b"abcdefgh",
            )
            .unwrap();
        config.validate_and_precompute().unwrap();
        assert!(matches!(config.credentials, UsmCredentials::MasterKeys(_)));
    }

    #[cfg(feature = "crypto-fips")]
    #[test]
    fn selected_fips_backend_rejects_unsupported_password_protocols() {
        assert!(matches!(
            UsmConfig::new("user")
                .with_crypto_backend(CryptoBackend::AwsLcFips)
                .unwrap()
                .auth(AuthProtocol::Md5, b"password"),
            Err(CryptoError::UnsupportedAlgorithm("MD5"))
        ));
        assert!(matches!(
            UsmConfig::new("user")
                .with_crypto_backend(CryptoBackend::AwsLcFips)
                .unwrap()
                .auth_priv(
                    AuthProtocol::Sha256,
                    b"password",
                    PrivProtocol::Des,
                    b"password",
                ),
            Err(CryptoError::UnsupportedAlgorithm("DES"))
        ));
    }

    #[cfg(all(feature = "crypto-fips", not(feature = "crypto-rustcrypto")))]
    #[test]
    fn fips_only_build_exposes_stable_backend_identities_and_capabilities() {
        assert_eq!(
            CryptoBackend::default_backend(),
            Some(CryptoBackend::AwsLcFips)
        );
        assert!(CryptoBackend::AwsLcFips.is_compiled());
        assert!(!CryptoBackend::RustCrypto.is_compiled());
        assert_eq!(
            UsmConfig::new("user")
                .with_crypto_backend(CryptoBackend::RustCrypto)
                .unwrap_err(),
            CryptoError::BackendNotCompiled(CryptoBackend::RustCrypto)
        );
    }

    #[cfg(feature = "crypto-fips")]
    #[test]
    fn selected_fips_backend_rejects_unsupported_master_key_privacy() {
        assert!(matches!(
            crate::v3::MasterKeys::new_with_backend(
                AuthProtocol::Sha256,
                b"password",
                CryptoBackend::AwsLcFips,
            )
            .unwrap()
            .with_privacy_same_password(PrivProtocol::Des),
            Err(CryptoError::UnsupportedAlgorithm("DES"))
        ));
    }

    #[cfg(all(feature = "crypto-rustcrypto", feature = "crypto-fips"))]
    #[test]
    fn selected_fips_backend_rejects_unsupported_master_key_auth() {
        let master_keys = crate::v3::MasterKeys::new_with_backend(
            AuthProtocol::Md5,
            b"password",
            CryptoBackend::RustCrypto,
        )
        .unwrap();
        let config = UsmConfig::new("user")
            .with_master_keys(master_keys)
            .unwrap()
            .with_crypto_backend(CryptoBackend::AwsLcFips);

        assert!(matches!(
            config,
            Err(CryptoError::UnsupportedAlgorithm("MD5"))
        ));
    }
}