Skip to main content

use_api_key/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(ApiKeyId);
109text_newtype!(ApiKeyPrefix);
110
111/// An API key value that redacts its debug representation.
112#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
113pub struct ApiKey(String);
114
115impl ApiKey {
116    /// Creates validated API key text metadata.
117    ///
118    /// # Errors
119    ///
120    /// Returns [`ApiPrimitiveError`] when the value is empty or contains control characters.
121    pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
122        validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
123    }
124
125    /// Parses validated API key text metadata.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`ApiPrimitiveError`] when validation fails.
130    pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
131        Self::new(value)
132    }
133
134    /// Returns the stored API key text.
135    #[must_use]
136    pub fn as_str(&self) -> &str {
137        &self.0
138    }
139
140    /// Consumes the key and returns the stored text.
141    #[must_use]
142    pub fn into_string(self) -> String {
143        self.0
144    }
145}
146
147impl AsRef<str> for ApiKey {
148    fn as_ref(&self) -> &str {
149        self.as_str()
150    }
151}
152
153impl fmt::Display for ApiKey {
154    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
155        formatter.write_str(self.as_str())
156    }
157}
158
159impl FromStr for ApiKey {
160    type Err = ApiPrimitiveError;
161
162    fn from_str(value: &str) -> Result<Self, Self::Err> {
163        Self::new(value)
164    }
165}
166
167impl TryFrom<&str> for ApiKey {
168    type Error = ApiPrimitiveError;
169
170    fn try_from(value: &str) -> Result<Self, Self::Error> {
171        Self::new(value)
172    }
173}
174
175text_newtype!(ApiKeyLabel);
176
177/// API key status labels.
178#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
179pub enum ApiKeyStatus {
180    /// A stable label variant.
181    Active,
182    /// A stable label variant.
183    Revoked,
184    /// A stable label variant.
185    Expired,
186    /// A stable label variant.
187    Suspended,
188}
189
190impl ApiKeyStatus {
191    /// Returns the stable label.
192    #[must_use]
193    pub const fn as_str(self) -> &'static str {
194        match self {
195            Self::Active => "active",
196            Self::Revoked => "revoked",
197            Self::Expired => "expired",
198            Self::Suspended => "suspended",
199        }
200    }
201}
202
203impl Default for ApiKeyStatus {
204    fn default() -> Self {
205        Self::Active
206    }
207}
208
209impl fmt::Display for ApiKeyStatus {
210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211        formatter.write_str(self.as_str())
212    }
213}
214
215impl FromStr for ApiKeyStatus {
216    type Err = ApiPrimitiveError;
217
218    fn from_str(value: &str) -> Result<Self, Self::Err> {
219        let trimmed = value.trim();
220        if trimmed.is_empty() {
221            return Err(ApiPrimitiveError::Empty);
222        }
223        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
224        match normalized.as_str() {
225            "active" => Ok(Self::Active),
226            "revoked" => Ok(Self::Revoked),
227            "expired" => Ok(Self::Expired),
228            "suspended" => Ok(Self::Suspended),
229            _ => Err(ApiPrimitiveError::Unknown),
230        }
231    }
232}
233
234/// Lightweight metadata tying this crate's primary text and label together.
235#[derive(Clone, Debug, Eq, PartialEq)]
236pub struct PrimitiveMetadata {
237    name: ApiKeyId,
238    kind: ApiKeyStatus,
239}
240
241impl PrimitiveMetadata {
242    /// Creates primitive metadata.
243    #[must_use]
244    pub const fn new(name: ApiKeyId, kind: ApiKeyStatus) -> Self {
245        Self { name, kind }
246    }
247
248    /// Returns the primary text value.
249    #[must_use]
250    pub const fn name(&self) -> &ApiKeyId {
251        &self.name
252    }
253
254    /// Returns the primary label.
255    #[must_use]
256    pub const fn kind(&self) -> ApiKeyStatus {
257        self.kind
258    }
259}
260
261impl fmt::Debug for ApiKey {
262    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
263        formatter.write_str("ApiKey(\"<redacted>\")")
264    }
265}
266
267impl ApiKey {
268    /// Returns a safely redacted key string.
269    #[must_use]
270    pub fn redacted(&self) -> String {
271        redact_api_key(self.as_str())
272    }
273}
274
275/// Redacts API key text while preserving short prefix context.
276#[must_use]
277pub fn redact_api_key(value: &str) -> String {
278    let trimmed = value.trim();
279    if trimmed.len() <= 8 {
280        return String::from("<redacted>");
281    }
282    let prefix = &trimmed[..4];
283    let suffix = &trimmed[trimmed.len() - 4..];
284    format!("{prefix}...{suffix}")
285}
286
287/// API key metadata.
288#[derive(Clone, Debug, Eq, PartialEq)]
289pub struct ApiKeyMetadata {
290    id: ApiKeyId,
291    prefix: ApiKeyPrefix,
292    status: ApiKeyStatus,
293}
294
295impl ApiKeyMetadata {
296    /// Creates API key metadata.
297    #[must_use]
298    pub const fn new(id: ApiKeyId, prefix: ApiKeyPrefix, status: ApiKeyStatus) -> Self {
299        Self { id, prefix, status }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
309        let value = ApiKeyId::new("sk_live_example")?;
310
311        assert_eq!(value.as_str(), "sk_live_example");
312        assert_eq!(value.to_string(), "sk_live_example");
313        assert_eq!("sk_live_example".parse::<ApiKeyId>()?, value);
314        Ok(())
315    }
316
317    #[test]
318    fn rejects_empty_text() {
319        assert_eq!(ApiKeyId::new(""), Err(ApiPrimitiveError::Empty));
320    }
321
322    #[test]
323    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
324        let kind = "active".parse::<ApiKeyStatus>()?;
325
326        assert_eq!(kind, ApiKeyStatus::Active);
327        assert_eq!(kind.to_string(), "active");
328        Ok(())
329    }
330
331    #[test]
332    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
333        let metadata =
334            PrimitiveMetadata::new(ApiKeyId::new("sk_live_example")?, ApiKeyStatus::default());
335
336        assert_eq!(metadata.name().as_str(), "sk_live_example");
337        assert_eq!(metadata.kind(), ApiKeyStatus::default());
338        Ok(())
339    }
340}