Skip to main content

rustfs_credentials/
credentials.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{DEFAULT_ACCESS_KEY, DEFAULT_SECRET_KEY, ENV_RPC_SECRET, IAM_POLICY_CLAIM_NAME_SA, INHERITED_POLICY_TYPE};
16use base64_simd::URL_SAFE_NO_PAD;
17use hmac::{Hmac, KeyInit, Mac};
18use rand::{Rng, RngExt};
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21use sha2::Sha256;
22use std::collections::HashMap;
23use std::env;
24use std::fmt;
25use std::io::Error;
26use std::sync::{LazyLock, OnceLock};
27use time::OffsetDateTime;
28
29/// Global active credentials
30static GLOBAL_ACTIVE_CRED: OnceLock<Credentials> = OnceLock::new();
31
32/// Global RPC authentication token
33static GLOBAL_RUSTFS_RPC_SECRET: OnceLock<String> = OnceLock::new();
34
35/// Public error returned when RPC authentication is not safely configured.
36pub const RPC_SECRET_REQUIRED_MESSAGE: &str = "RPC authentication secret is not configured";
37
38/// Operator-facing guidance for configuring RPC authentication safely.
39pub const RPC_SECRET_REQUIRED_OPERATOR_MESSAGE: &str =
40    "RUSTFS_RPC_SECRET can be set explicitly; otherwise the RPC secret is derived from the active access/secret key pair";
41
42type HmacSha256 = Hmac<Sha256>;
43
44const RPC_SECRET_DERIVATION_CONTEXT: &[u8] = b"rustfs-rpc-secret:v1";
45
46/// Error type for credentials operations
47#[derive(Debug)]
48pub enum CredentialsError {
49    /// Credentials already initialized
50    AlreadyInitialized,
51    /// Failed to generate access key
52    AccessKeyGenerationFailed(Error),
53    /// Failed to generate secret key
54    SecretKeyGenerationFailed(Error),
55}
56
57impl fmt::Display for CredentialsError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            CredentialsError::AlreadyInitialized => write!(f, "Credentials already initialized"),
61            CredentialsError::AccessKeyGenerationFailed(e) => write!(f, "Failed to generate access key: {}", e),
62            CredentialsError::SecretKeyGenerationFailed(e) => write!(f, "Failed to generate secret key: {}", e),
63        }
64    }
65}
66
67impl std::error::Error for CredentialsError {
68    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69        match self {
70            CredentialsError::AccessKeyGenerationFailed(e) => Some(e),
71            CredentialsError::SecretKeyGenerationFailed(e) => Some(e),
72            _ => None,
73        }
74    }
75}
76
77/// Initialize the global action credentials
78///
79/// # Arguments
80/// * `ak` - Optional access key
81/// * `sk` - Optional secret key
82///
83/// # Returns
84/// * `Result<(), CredentialsError>` - Ok if successful, Err if already initialized or generation failed
85pub fn init_global_action_credentials(ak: Option<String>, sk: Option<String>) -> Result<(), CredentialsError> {
86    let ak = match ak {
87        Some(k) => k,
88        None => gen_access_key(20).map_err(CredentialsError::AccessKeyGenerationFailed)?,
89    };
90
91    let sk = match sk {
92        Some(k) => k,
93        None => gen_secret_key(32).map_err(CredentialsError::SecretKeyGenerationFailed)?,
94    };
95
96    let cred = Credentials {
97        access_key: ak,
98        secret_key: sk,
99        ..Default::default()
100    };
101
102    GLOBAL_ACTIVE_CRED.set(cred).map_err(|_| CredentialsError::AlreadyInitialized)
103}
104
105/// Get the global action credentials
106pub fn get_global_action_cred() -> Option<Credentials> {
107    GLOBAL_ACTIVE_CRED.get().cloned()
108}
109
110/// Get the global secret key
111///
112/// # Returns
113/// * `Option<String>` - The global secret key, if set
114///
115pub fn get_global_secret_key_opt() -> Option<String> {
116    GLOBAL_ACTIVE_CRED.get().map(|cred| cred.secret_key.clone())
117}
118
119/// Get the global secret key
120///
121/// # Returns
122/// * `String` - The global secret key, or empty string if not set
123///
124pub fn get_global_secret_key() -> String {
125    GLOBAL_ACTIVE_CRED
126        .get()
127        .map(|cred| cred.secret_key.clone())
128        .unwrap_or_default()
129}
130
131/// Get the global access key
132///
133/// # Returns
134/// * `Option<String>` - The global access key, if set
135///
136pub fn get_global_access_key_opt() -> Option<String> {
137    GLOBAL_ACTIVE_CRED.get().map(|cred| cred.access_key.clone())
138}
139
140/// Get the global access key
141///
142/// # Returns
143/// * `String` - The global access key, or empty string if not set
144///
145pub fn get_global_access_key() -> String {
146    GLOBAL_ACTIVE_CRED
147        .get()
148        .map(|cred| cred.access_key.clone())
149        .unwrap_or_default()
150}
151
152/// Generates a random access key of the specified length.
153///
154/// # Arguments
155/// * `length` - The length of the access key to generate
156///
157/// # Returns
158/// * `Result<String>` - A result containing the generated access key or an error if the length is too short
159///
160/// # Errors
161/// This function will return an error if the specified length is less than 3.
162///
163/// Examples
164/// ```no_run
165/// use rustfs_credentials::gen_access_key;
166///
167/// let access_key = gen_access_key(16).unwrap();
168/// println!("Generated access key: {}", access_key);
169/// ```
170///
171pub fn gen_access_key(length: usize) -> std::io::Result<String> {
172    const ALPHA_NUMERIC_TABLE: [char; 36] = [
173        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
174        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
175    ];
176
177    if length < 3 {
178        return Err(Error::other("access key length is too short"));
179    }
180
181    let mut result = String::with_capacity(length);
182    let mut rng = rand::rng();
183
184    for _ in 0..length {
185        result.push(ALPHA_NUMERIC_TABLE[rng.random_range(0..ALPHA_NUMERIC_TABLE.len())]);
186    }
187
188    Ok(result)
189}
190
191/// Generates a random secret key of the specified length.
192///
193/// # Arguments
194/// * `length` - The length of the secret key to generate
195///
196/// # Returns
197/// * `Result<String>` - A result containing the generated secret key or an error if the length is too short
198///
199/// # Errors
200/// This function will return an error if the specified length is less than 8.
201///
202/// # Examples
203/// ```no_run
204/// use rustfs_credentials::gen_secret_key;
205///
206/// let secret_key = gen_secret_key(32).unwrap();
207/// println!("Generated secret key: {}", secret_key);
208/// ```
209///
210pub fn gen_secret_key(length: usize) -> std::io::Result<String> {
211    use base64_simd::URL_SAFE_NO_PAD;
212
213    if length < 8 {
214        return Err(Error::other("secret key length is too short"));
215    }
216    let mut rng = rand::rng();
217
218    let mut key = vec![0u8; URL_SAFE_NO_PAD.estimated_decoded_length(length)];
219    rng.fill_bytes(&mut key);
220
221    // URL_SAFE_NO_PAD uses "-" and "_" instead of "+" and "/", so "/" never
222    // appears in the output. The .replace("/", "+") was a dead no-op.
223    let encoded = URL_SAFE_NO_PAD.encode_to_string(&key);
224
225    Ok(encoded)
226}
227
228/// Get the RPC authentication token from the environment or derive it from the active credentials.
229///
230/// # Returns
231/// * `String` - The RPC authentication token
232///
233fn normalize_rpc_secret(secret: &str) -> Option<String> {
234    let secret = secret.trim();
235    (!secret.is_empty() && secret != DEFAULT_SECRET_KEY && secret != DEFAULT_ACCESS_KEY).then(|| secret.to_string())
236}
237
238fn derive_rpc_secret(access_key: &str, secret_key: &str) -> Option<String> {
239    let access_key = access_key.trim();
240    let secret_key = secret_key.trim();
241
242    if access_key.is_empty() || secret_key.is_empty() {
243        return None;
244    }
245
246    let Ok(mut mac) = <HmacSha256 as KeyInit>::new_from_slice(secret_key.as_bytes()) else {
247        return None;
248    };
249    mac.update(RPC_SECRET_DERIVATION_CONTEXT);
250    mac.update(&[0]);
251    mac.update(access_key.as_bytes());
252
253    Some(URL_SAFE_NO_PAD.encode_to_string(mac.finalize().into_bytes()))
254}
255
256fn resolve_rpc_secret(env_secret: Option<&str>, global_access: Option<&str>, global_secret: Option<&str>) -> Option<String> {
257    if let Some(secret) = env_secret.map(str::trim).filter(|secret| !secret.is_empty()) {
258        return normalize_rpc_secret(secret);
259    }
260
261    match (global_access, global_secret) {
262        (Some(access_key), Some(secret_key)) => {
263            // Fail closed when either half of the active credential pair still
264            // uses the public default. Operators must configure both custom
265            // credentials or provide RUSTFS_RPC_SECRET explicitly.
266            if access_key.trim() == DEFAULT_ACCESS_KEY || secret_key.trim() == DEFAULT_SECRET_KEY {
267                return None;
268            }
269            derive_rpc_secret(access_key, secret_key)
270        }
271        _ => None,
272    }
273}
274
275pub fn set_global_rpc_secret(secret: String) -> Result<(), String> {
276    GLOBAL_RUSTFS_RPC_SECRET.set(secret)
277}
278
279pub fn try_get_rpc_token() -> std::io::Result<String> {
280    if let Some(secret) = GLOBAL_RUSTFS_RPC_SECRET.get() {
281        return normalize_rpc_secret(secret).ok_or_else(|| Error::other(RPC_SECRET_REQUIRED_MESSAGE));
282    }
283
284    let env_secret = env::var(ENV_RPC_SECRET).ok();
285    let global_access = get_global_access_key_opt();
286    let global_secret = get_global_secret_key_opt();
287    let secret = resolve_rpc_secret(env_secret.as_deref(), global_access.as_deref(), global_secret.as_deref())
288        .ok_or_else(|| Error::other(RPC_SECRET_REQUIRED_MESSAGE))?;
289
290    match GLOBAL_RUSTFS_RPC_SECRET.set(secret.clone()) {
291        Ok(()) => Ok(secret),
292        Err(_) => GLOBAL_RUSTFS_RPC_SECRET
293            .get()
294            .and_then(|stored| normalize_rpc_secret(stored))
295            .ok_or_else(|| Error::other(RPC_SECRET_REQUIRED_MESSAGE)),
296    }
297}
298
299#[deprecated(note = "use try_get_rpc_token to handle missing RPC secrets explicitly")]
300pub fn get_rpc_token() -> String {
301    try_get_rpc_token().unwrap_or_default()
302}
303
304/// A wrapper struct for masking sensitive strings in Debug implementations.
305/// It avoids allocating a new String just for formatting.
306pub struct Masked<'a>(pub Option<&'a str>);
307
308impl<'a> fmt::Debug for Masked<'a> {
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        match self.0 {
311            None => Ok(()),
312            Some(s) => {
313                let len = s.chars().count();
314                if len == 0 {
315                    Ok(())
316                } else if len == 1 {
317                    write!(f, "***")
318                } else if len == 2 {
319                    let first = s.chars().next().ok_or(fmt::Error)?;
320                    write!(f, "{}***|{}", first, len)
321                } else {
322                    let first = s.chars().next().ok_or(fmt::Error)?;
323                    let last = s.chars().last().ok_or(fmt::Error)?;
324                    write!(f, "{}***{}|{}", first, last, len)
325                }
326            }
327        }
328    }
329}
330
331impl<'a> fmt::Display for Masked<'a> {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        fmt::Debug::fmt(self, f)
334    }
335}
336
337/// Credentials structure
338///
339/// Fields:
340/// - access_key: Access key string
341/// - secret_key: Secret key string
342/// - session_token: Session token string
343/// - expiration: Optional expiration time as OffsetDateTime
344/// - status: Status string (e.g., "active", "off")
345/// - parent_user: Parent user string
346/// - groups: Optional list of groups
347/// - claims: Optional map of claims
348/// - name: Optional name string
349/// - description: Optional description string
350///
351#[derive(Serialize, Deserialize, Clone, Default)]
352pub struct Credentials {
353    #[serde(rename = "accessKey", alias = "access_key", default)]
354    pub access_key: String,
355    #[serde(rename = "secretKey", alias = "secret_key", default)]
356    pub secret_key: String,
357    #[serde(rename = "sessionToken", alias = "session_token", default)]
358    pub session_token: String,
359    #[serde(default, with = "crate::serde_datetime::option")]
360    pub expiration: Option<OffsetDateTime>,
361    #[serde(default)]
362    pub status: String,
363    #[serde(rename = "parentUser", alias = "parent_user", default)]
364    pub parent_user: String,
365    #[serde(default)]
366    pub groups: Option<Vec<String>>,
367    #[serde(default)]
368    pub claims: Option<HashMap<String, Value>>,
369    #[serde(default)]
370    pub name: Option<String>,
371    #[serde(default)]
372    pub description: Option<String>,
373}
374
375impl fmt::Debug for Credentials {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        f.debug_struct("Credentials")
378            .field("access_key", &self.access_key)
379            .field("secret_key", &Masked(Some(&self.secret_key)))
380            .field("session_token", &Masked(Some(&self.session_token)))
381            .field("expiration", &self.expiration)
382            .field("status", &self.status)
383            .field("parent_user", &self.parent_user)
384            .field("groups", &self.groups)
385            .field("claims", &self.claims)
386            .field("name", &self.name)
387            .field("description", &self.description)
388            .finish()
389    }
390}
391
392impl Credentials {
393    /// Returns a reference to this credential's claims, or a shared empty map
394    /// when the credential has no claims attached. Avoids per-call allocation
395    /// at call sites that need an `&HashMap<String, Value>`.
396    pub fn claims_or_empty(&self) -> &HashMap<String, Value> {
397        static EMPTY: LazyLock<HashMap<String, Value>> = LazyLock::new(HashMap::new);
398        match &self.claims {
399            Some(c) => c,
400            None => &EMPTY,
401        }
402    }
403
404    pub fn is_expired(&self) -> bool {
405        if self.expiration.is_none() {
406            return false;
407        }
408
409        self.expiration
410            .as_ref()
411            .map(|e| OffsetDateTime::now_utc() > *e)
412            .unwrap_or(false)
413    }
414
415    pub fn is_temp(&self) -> bool {
416        !self.session_token.is_empty() && !self.is_expired()
417    }
418
419    pub fn is_service_account(&self) -> bool {
420        self.claims
421            .as_ref()
422            .map(|x| x.get(IAM_POLICY_CLAIM_NAME_SA).is_some_and(|_| !self.parent_user.is_empty()))
423            .unwrap_or_default()
424    }
425
426    pub fn is_implied_policy(&self) -> bool {
427        if self.is_service_account() {
428            return self
429                .claims
430                .as_ref()
431                .map(|x| x.get(IAM_POLICY_CLAIM_NAME_SA).is_some_and(|v| v == INHERITED_POLICY_TYPE))
432                .unwrap_or_default();
433        }
434
435        false
436    }
437
438    pub fn is_valid(&self) -> bool {
439        if self.status == "off" {
440            return false;
441        }
442
443        self.access_key.len() >= 3 && self.secret_key.len() >= 8 && !self.is_expired()
444    }
445
446    pub fn is_owner(&self) -> bool {
447        false
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use crate::{DEFAULT_ACCESS_KEY, IAM_POLICY_CLAIM_NAME_SA, INHERITED_POLICY_TYPE};
455    use time::Duration;
456
457    #[test]
458    fn test_credentials_is_expired() {
459        let mut cred = Credentials::default();
460        assert!(!cred.is_expired());
461
462        cred.expiration = Some(OffsetDateTime::now_utc() + Duration::hours(1));
463        assert!(!cred.is_expired());
464
465        cred.expiration = Some(OffsetDateTime::now_utc() - Duration::hours(1));
466        assert!(cred.is_expired());
467    }
468
469    #[test]
470    fn test_credentials_is_temp() {
471        let mut cred = Credentials::default();
472        assert!(!cred.is_temp());
473
474        cred.session_token = "token".to_string();
475        assert!(cred.is_temp());
476
477        cred.expiration = Some(OffsetDateTime::now_utc() - Duration::hours(1));
478        assert!(!cred.is_temp());
479    }
480
481    #[test]
482    fn test_credentials_is_service_account() {
483        let mut cred = Credentials::default();
484        assert!(!cred.is_service_account());
485
486        let mut claims = HashMap::new();
487        claims.insert(IAM_POLICY_CLAIM_NAME_SA.to_string(), Value::String("policy".to_string()));
488        cred.claims = Some(claims);
489        cred.parent_user = "parent".to_string();
490        assert!(cred.is_service_account());
491    }
492
493    #[test]
494    fn test_credentials_is_implied_policy() {
495        let mut cred = Credentials::default();
496        assert!(!cred.is_implied_policy());
497
498        let mut claims = HashMap::new();
499        claims.insert(IAM_POLICY_CLAIM_NAME_SA.to_string(), Value::String(INHERITED_POLICY_TYPE.to_string()));
500        cred.claims = Some(claims);
501        cred.parent_user = "parent".to_string();
502        assert!(cred.is_implied_policy());
503    }
504
505    #[test]
506    fn test_credentials_is_valid() {
507        let mut cred = Credentials::default();
508        assert!(!cred.is_valid());
509
510        cred.access_key = "abc".to_string();
511        cred.secret_key = "12345678".to_string();
512        assert!(cred.is_valid());
513
514        cred.status = "off".to_string();
515        assert!(!cred.is_valid());
516    }
517
518    #[test]
519    fn test_credentials_is_owner() {
520        let cred = Credentials::default();
521        assert!(!cred.is_owner());
522    }
523
524    #[test]
525    fn test_global_credentials_flow() {
526        // Since OnceLock can only be set once, we put together all globally related tests
527        // If it has already been initialized (possibly from other tests), we verify the results directly
528        if get_global_action_cred().is_none() {
529            // Verify that the initial state is empty
530            assert!(get_global_access_key_opt().is_none());
531            assert_eq!(get_global_access_key(), "");
532            assert!(get_global_secret_key_opt().is_none());
533            assert_eq!(get_global_secret_key(), "");
534
535            // Initialize
536            let test_ak = "test_access_key".to_string();
537            let test_sk = "test_secret_key_123456".to_string();
538            init_global_action_credentials(Some(test_ak), Some(test_sk)).ok();
539        }
540
541        // Verify the state after initialization
542        let cred = get_global_action_cred().expect("Global credentials should be set");
543        assert!(!cred.access_key.is_empty());
544        assert!(!cred.secret_key.is_empty());
545
546        assert!(get_global_access_key_opt().is_some());
547        assert!(!get_global_access_key().is_empty());
548        assert!(get_global_secret_key_opt().is_some());
549        assert!(!get_global_secret_key().is_empty());
550    }
551
552    #[test]
553    fn test_init_global_credentials_auto_gen() {
554        // If it hasn't already been initialized, the test automatically generates logic
555        if get_global_action_cred().is_none() {
556            init_global_action_credentials(None, None).ok();
557        }
558
559        let ak = get_global_access_key();
560        let sk = get_global_secret_key();
561        assert!(ak.len() >= 3);
562        assert!(sk.len() >= 8);
563    }
564
565    #[test]
566    fn test_gen_secret_key_uses_url_safe_base64_without_padding() {
567        let key = gen_secret_key(32).expect("secret key should generate");
568
569        assert_eq!(key.len(), 32);
570        assert!(!key.contains('/'));
571        assert!(!key.contains('+'));
572        assert!(!key.contains('='));
573    }
574
575    #[test]
576    fn test_gen_access_key_length_and_charset() {
577        let err = gen_access_key(2).expect_err("length below 3 should fail");
578        assert_eq!(err.to_string(), "access key length is too short");
579
580        let key = gen_access_key(20).expect("access key should generate");
581        assert_eq!(key.len(), 20);
582        assert!(key.chars().all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit()));
583    }
584
585    #[test]
586    fn test_resolve_rpc_secret_rejects_default_credentials_for_derivation() {
587        assert!(resolve_rpc_secret(None, None, None).is_none());
588
589        // Fail closed when either half of the credential pair uses the public
590        // default.
591        assert!(resolve_rpc_secret(None, Some(DEFAULT_ACCESS_KEY), Some(DEFAULT_SECRET_KEY)).is_none());
592        assert!(resolve_rpc_secret(None, Some(DEFAULT_ACCESS_KEY), Some("custom-global-secret")).is_none());
593        assert!(resolve_rpc_secret(None, Some("custom-access"), Some(DEFAULT_SECRET_KEY)).is_none());
594
595        assert!(resolve_rpc_secret(Some(DEFAULT_SECRET_KEY), Some("custom-access"), Some("custom-global-secret")).is_none());
596    }
597
598    #[test]
599    fn test_rpc_secret_public_error_omits_configuration_details() {
600        assert!(!RPC_SECRET_REQUIRED_MESSAGE.contains("RUSTFS_"));
601        assert!(!RPC_SECRET_REQUIRED_MESSAGE.contains(DEFAULT_SECRET_KEY));
602        assert!(RPC_SECRET_REQUIRED_OPERATOR_MESSAGE.contains("RUSTFS_RPC_SECRET"));
603    }
604
605    #[allow(deprecated)]
606    #[test]
607    fn test_get_rpc_token_preserves_string_return_type() {
608        fn assert_string_return(_: fn() -> String) {}
609
610        assert_string_return(get_rpc_token);
611    }
612
613    #[allow(deprecated)]
614    #[test]
615    fn test_get_rpc_token_matches_fallible_api_contract() {
616        match try_get_rpc_token() {
617            Ok(secret) => assert_eq!(get_rpc_token(), secret),
618            Err(_) => assert_eq!(get_rpc_token(), ""),
619        }
620    }
621
622    #[test]
623    fn test_resolve_rpc_secret_accepts_non_default_secret() {
624        assert_eq!(
625            resolve_rpc_secret(Some("custom-rpc-secret"), None, None).as_deref(),
626            Some("custom-rpc-secret")
627        );
628        assert_eq!(
629            resolve_rpc_secret(Some("custom-rpc-secret"), Some(DEFAULT_ACCESS_KEY), Some(DEFAULT_SECRET_KEY)).as_deref(),
630            Some("custom-rpc-secret")
631        );
632        let expected = derive_rpc_secret("custom-access", "custom-global-secret").expect("secret should derive");
633        assert_eq!(
634            resolve_rpc_secret(None, Some("custom-access"), Some("custom-global-secret")).as_deref(),
635            Some(expected.as_str())
636        );
637    }
638
639    #[test]
640    fn test_resolve_rpc_secret_trims_and_falls_back_from_blank_env() {
641        let expected = derive_rpc_secret("custom-access", "custom-global-secret").expect("secret should derive");
642        assert_eq!(
643            resolve_rpc_secret(Some("  custom-rpc-secret  "), None, None).as_deref(),
644            Some("custom-rpc-secret")
645        );
646        assert_eq!(
647            resolve_rpc_secret(Some(""), Some("custom-access"), Some("custom-global-secret")).as_deref(),
648            Some(expected.as_str())
649        );
650        assert_eq!(
651            resolve_rpc_secret(Some("  "), Some("  custom-access  "), Some("  custom-global-secret  ")).as_deref(),
652            Some(expected.as_str())
653        );
654        assert_eq!(
655            resolve_rpc_secret(Some("  "), Some("custom-access"), Some("custom-global-secret")).as_deref(),
656            Some(expected.as_str())
657        );
658    }
659
660    #[test]
661    fn test_resolve_rpc_secret_returns_none_for_trimmed_default_secret() {
662        let padded_default_secret = format!("  {}  ", DEFAULT_SECRET_KEY);
663        assert!(
664            resolve_rpc_secret(Some(padded_default_secret.as_str()), Some("custom-access"), Some("custom-global-secret"))
665                .is_none()
666        );
667
668        let padded_default_access = format!("  {}  ", DEFAULT_ACCESS_KEY);
669        assert!(
670            resolve_rpc_secret(Some(padded_default_access.as_str()), Some("custom-access"), Some("custom-global-secret"))
671                .is_none()
672        );
673    }
674
675    #[test]
676    fn test_derive_rpc_secret_is_stable_and_not_plaintext() {
677        let first = derive_rpc_secret("custom-access", "custom-secret").expect("secret should derive");
678        let second = derive_rpc_secret("custom-access", "custom-secret").expect("secret should derive");
679
680        assert_eq!(first, second);
681        assert_ne!(first, "custom-access");
682        assert_ne!(first, "custom-secret");
683        assert_ne!(first, format!("{}{}", "custom-access", "custom-secret"));
684        assert!(!first.contains("custom-access"));
685        assert!(!first.contains("custom-secret"));
686    }
687
688    #[test]
689    fn test_masked_debug() {
690        // Test None
691        assert_eq!(format!("{:?}", Masked(None)), "");
692
693        // Test empty string
694        assert_eq!(format!("{:?}", Masked(Some(""))), "");
695
696        // Test length 1
697        assert_eq!(format!("{:?}", Masked(Some("a"))), "***");
698
699        // Test length 2
700        assert_eq!(format!("{:?}", Masked(Some("ab"))), "a***|2");
701
702        // Test length 3
703        assert_eq!(format!("{:?}", Masked(Some("abc"))), "a***c|3");
704
705        // Test length 4
706        assert_eq!(format!("{:?}", Masked(Some("abcd"))), "a***d|4");
707
708        // Test longer string
709        assert_eq!(format!("{:?}", Masked(Some("secretpassword"))), "s***d|14");
710
711        // Test Unicode input should not panic and should keep character boundary
712        assert_eq!(format!("{:?}", Masked(Some("中"))), "***");
713        assert_eq!(format!("{:?}", Masked(Some("中文"))), "中***|2");
714        assert_eq!(format!("{:?}", Masked(Some("中文测试"))), "中***试|4");
715    }
716
717    #[test]
718    fn test_credentials_debug_masks_sensitive_fields() {
719        let cred = Credentials {
720            access_key: "debug-access-key".to_string(),
721            secret_key: "debug-secret-key".to_string(),
722            session_token: "debug-session-token".to_string(),
723            parent_user: "parent-user".to_string(),
724            ..Default::default()
725        };
726
727        let output = format!("{cred:?}");
728
729        assert!(output.contains("debug-access-key"));
730        assert!(output.contains("parent-user"));
731        assert!(!output.contains("debug-secret-key"));
732        assert!(!output.contains("debug-session-token"));
733    }
734
735    #[test]
736    fn test_credentials_expiration_serialize_as_rfc3339() {
737        use time::OffsetDateTime;
738
739        let c = Credentials {
740            access_key: "ak".to_string(),
741            secret_key: "sk12345678".to_string(),
742            expiration: Some(OffsetDateTime::now_utc()),
743            ..Default::default()
744        };
745
746        let json = serde_json::to_string(&c).expect("serialize");
747        assert!(
748            json.contains('T') && (json.contains('Z') || json.contains("+00:00")),
749            "Credentials expiration should be RFC3339; got: {}",
750            json
751        );
752    }
753
754    #[test]
755    fn test_credentials_deserialize_minio_style_rfc3339_expiration() {
756        let minio_style = r#"{"accessKey":"ak","secretKey":"sk12345678","expiration":"2025-03-07T12:00:00Z"}"#;
757        let c: Credentials = serde_json::from_str(minio_style).expect("deserialize");
758        assert_eq!(c.access_key, "ak");
759        assert!(c.expiration.is_some());
760    }
761}