Skip to main content

uz_types/
secret.rs

1//! Sir tiplari: `AccessToken`, `RefreshToken`, `ClientSecret`.
2//!
3//! Sir tiplarida **yo'q**: `Display`, `AsRef<str>`, `Borrow<str>`, `Deref`, `into_inner`,
4//! derive `PartialEq`, `Hash`, `Ord`, (default'da) `Serialize`.
5//! **Bor**: `expose_secret()`, yashirilgan `Debug`, constant-time `PartialEq` (`subtle`),
6//! `Deserialize` (serde), `Serialize` faqat `serialize-secrets` feature'da,
7//! `zeroize` feature'da `Drop` xotirani tozalaydi.
8
9/// Token / sir uzunligi chegarasi (bayt). 8 KiB — JWT/Bearer uchun yetarli.
10///
11/// Diqqat: bu **xotira DoS'idan himoya emas** — `String` bu tekshiruvga kelguncha
12/// allaqachon ajratilgan bo'ladi; body-limit HTTP qatlamida turishi kerak.
13pub const MAX_TOKEN_LEN: usize = 8192;
14
15/// Token / sir xatolari.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
17#[non_exhaustive]
18pub enum TokenError {
19    /// Trim'dan keyin bo'sh.
20    #[error("token cannot be empty")]
21    Empty,
22    /// `MAX_TOKEN_LEN` dan uzun.
23    #[error("token is too long, maximum is {MAX_TOKEN_LEN} bytes")]
24    TooLong,
25}
26
27fn validate_token(s: &str) -> Result<(), TokenError> {
28    if s.is_empty() {
29        return Err(TokenError::Empty);
30    }
31    if s.len() > MAX_TOKEN_LEN {
32        return Err(TokenError::TooLong);
33    }
34    Ok(())
35}
36
37macro_rules! secret_newtype {
38    (
39        $(#[$meta:meta])*
40        $vis:vis struct $Name:ident;
41    ) => {
42        $(#[$meta])*
43        #[derive(Clone)]
44        $vis struct $Name(String);
45
46        impl $Name {
47            /// Ruxsat etilgan maksimal uzunlik — [`MAX_TOKEN_LEN`].
48            pub const MAX_LEN: usize = MAX_TOKEN_LEN;
49
50            /// Trim → validatsiya. Bitta allocation.
51            pub fn parse(value: &str) -> Result<Self, TokenError> {
52                Self::try_from(value.to_owned())
53            }
54
55            /// Sirni **ochiq** qaytaradi. Nomi ataylab uzun — code review'da ko'zga tashlanadi.
56            #[inline]
57            #[must_use]
58            pub fn expose_secret(&self) -> &str {
59                &self.0
60            }
61        }
62
63        impl TryFrom<String> for $Name {
64            type Error = TokenError;
65
66            fn try_from(mut value: String) -> Result<Self, TokenError> {
67                $crate::macros::trim_in_place(&mut value);
68                match validate_token(&value) {
69                    Ok(()) => Ok(Self(value)),
70                    Err(e) => {
71                        // Rad etilgan sir ham xotirada qolmasin.
72                        #[cfg(feature = "zeroize")]
73                        ::zeroize::Zeroize::zeroize(&mut value);
74                        Err(e)
75                    }
76                }
77            }
78        }
79
80        impl TryFrom<&str> for $Name {
81            type Error = TokenError;
82            fn try_from(value: &str) -> Result<Self, TokenError> {
83                Self::parse(value)
84            }
85        }
86
87        impl ::core::str::FromStr for $Name {
88            type Err = TokenError;
89            fn from_str(s: &str) -> Result<Self, TokenError> {
90                Self::parse(s)
91            }
92        }
93
94        /// Loglarda sir hech qachon ko'rinmaydi.
95        impl ::core::fmt::Debug for $Name {
96            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
97                f.write_str(concat!(stringify!($Name), "([REDACTED])"))
98            }
99        }
100
101        /// Constant-time taqqoslash — timing side-channel yo'q (uzunlik farqi bundan mustasno).
102        impl PartialEq for $Name {
103            fn eq(&self, other: &Self) -> bool {
104                ::subtle::ConstantTimeEq::ct_eq(self.0.as_bytes(), other.0.as_bytes()).into()
105            }
106        }
107        impl Eq for $Name {}
108
109        #[cfg(feature = "zeroize")]
110        impl Drop for $Name {
111            fn drop(&mut self) {
112                ::zeroize::Zeroize::zeroize(&mut self.0);
113            }
114        }
115
116        #[cfg(feature = "serde")]
117        impl<'de> ::serde::Deserialize<'de> for $Name {
118            fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
119                $crate::serde_support::deserialize_string_newtype(deserializer, "a non-empty secret string")
120            }
121        }
122
123        /// Faqat `serialize-secrets` feature'da — masalan, auth-servis token javobi uchun.
124        #[cfg(feature = "serialize-secrets")]
125        impl ::serde::Serialize for $Name {
126            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127                serializer.serialize_str(&self.0)
128            }
129        }
130    };
131}
132
133secret_newtype! {
134    /// Qisqa muddatli kirish tokeni (JWT/Bearer).
135    pub struct AccessToken;
136}
137
138secret_newtype! {
139    /// Uzoq muddatli yangilash tokeni.
140    pub struct RefreshToken;
141}
142
143secret_newtype! {
144    /// OAuth client secret.
145    pub struct ClientSecret;
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn secrets_are_redacted_and_ct_eq() {
154        let a = AccessToken::parse(" top-secret ").unwrap();
155        let b = AccessToken::parse("top-secret").unwrap();
156        assert_eq!(a, b);
157        assert_eq!(a.expose_secret(), "top-secret");
158        assert_eq!(format!("{a:?}"), "AccessToken([REDACTED])");
159        assert_eq!(AccessToken::parse("   "), Err(TokenError::Empty));
160        assert_eq!(
161            AccessToken::parse(&"a".repeat(MAX_TOKEN_LEN + 1)),
162            Err(TokenError::TooLong)
163        );
164    }
165}