1pub const MAX_TOKEN_LEN: usize = 8192;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
17#[non_exhaustive]
18pub enum TokenError {
19 #[error("token cannot be empty")]
21 Empty,
22 #[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 pub const MAX_LEN: usize = MAX_TOKEN_LEN;
49
50 pub fn parse(value: &str) -> Result<Self, TokenError> {
52 Self::try_from(value.to_owned())
53 }
54
55 #[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 #[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 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 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 #[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 pub struct AccessToken;
136}
137
138secret_newtype! {
139 pub struct RefreshToken;
141}
142
143secret_newtype! {
144 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}