Skip to main content

use_api_auth/
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!(AuthSchemeName);
109text_newtype!(BearerTokenMetadata);
110text_newtype!(OAuthScopeLabel);
111text_newtype!(PermissionScope);
112
113/// API key location labels.
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum ApiKeyLocation {
116    /// A stable label variant.
117    Header,
118    /// A stable label variant.
119    Query,
120    /// A stable label variant.
121    Cookie,
122    /// A stable label variant.
123    Body,
124}
125
126impl ApiKeyLocation {
127    /// Returns the stable label.
128    #[must_use]
129    pub const fn as_str(self) -> &'static str {
130        match self {
131            Self::Header => "header",
132            Self::Query => "query",
133            Self::Cookie => "cookie",
134            Self::Body => "body",
135        }
136    }
137}
138
139impl Default for ApiKeyLocation {
140    fn default() -> Self {
141        Self::Header
142    }
143}
144
145impl fmt::Display for ApiKeyLocation {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151impl FromStr for ApiKeyLocation {
152    type Err = ApiPrimitiveError;
153
154    fn from_str(value: &str) -> Result<Self, Self::Err> {
155        let trimmed = value.trim();
156        if trimmed.is_empty() {
157            return Err(ApiPrimitiveError::Empty);
158        }
159        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
160        match normalized.as_str() {
161            "header" => Ok(Self::Header),
162            "query" => Ok(Self::Query),
163            "cookie" => Ok(Self::Cookie),
164            "body" => Ok(Self::Body),
165            _ => Err(ApiPrimitiveError::Unknown),
166        }
167    }
168}
169/// Basic auth marker labels.
170#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
171pub enum BasicAuthMarker {
172    /// A stable label variant.
173    Present,
174    /// A stable label variant.
175    Absent,
176}
177
178impl BasicAuthMarker {
179    /// Returns the stable label.
180    #[must_use]
181    pub const fn as_str(self) -> &'static str {
182        match self {
183            Self::Present => "present",
184            Self::Absent => "absent",
185        }
186    }
187}
188
189impl Default for BasicAuthMarker {
190    fn default() -> Self {
191        Self::Present
192    }
193}
194
195impl fmt::Display for BasicAuthMarker {
196    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
197        formatter.write_str(self.as_str())
198    }
199}
200
201impl FromStr for BasicAuthMarker {
202    type Err = ApiPrimitiveError;
203
204    fn from_str(value: &str) -> Result<Self, Self::Err> {
205        let trimmed = value.trim();
206        if trimmed.is_empty() {
207            return Err(ApiPrimitiveError::Empty);
208        }
209        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
210        match normalized.as_str() {
211            "present" => Ok(Self::Present),
212            "absent" => Ok(Self::Absent),
213            _ => Err(ApiPrimitiveError::Unknown),
214        }
215    }
216}
217
218/// Lightweight metadata tying this crate's primary text and label together.
219#[derive(Clone, Debug, Eq, PartialEq)]
220pub struct PrimitiveMetadata {
221    name: AuthSchemeName,
222    kind: ApiKeyLocation,
223}
224
225impl PrimitiveMetadata {
226    /// Creates primitive metadata.
227    #[must_use]
228    pub const fn new(name: AuthSchemeName, kind: ApiKeyLocation) -> Self {
229        Self { name, kind }
230    }
231
232    /// Returns the primary text value.
233    #[must_use]
234    pub const fn name(&self) -> &AuthSchemeName {
235        &self.name
236    }
237
238    /// Returns the primary label.
239    #[must_use]
240    pub const fn kind(&self) -> ApiKeyLocation {
241        self.kind
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
251        let value = AuthSchemeName::new("Bearer")?;
252
253        assert_eq!(value.as_str(), "Bearer");
254        assert_eq!(value.to_string(), "Bearer");
255        assert_eq!("Bearer".parse::<AuthSchemeName>()?, value);
256        Ok(())
257    }
258
259    #[test]
260    fn rejects_empty_text() {
261        assert_eq!(AuthSchemeName::new(""), Err(ApiPrimitiveError::Empty));
262    }
263
264    #[test]
265    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
266        let kind = "header".parse::<ApiKeyLocation>()?;
267
268        assert_eq!(kind, ApiKeyLocation::Header);
269        assert_eq!(kind.to_string(), "header");
270        Ok(())
271    }
272
273    #[test]
274    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
275        let metadata =
276            PrimitiveMetadata::new(AuthSchemeName::new("Bearer")?, ApiKeyLocation::default());
277
278        assert_eq!(metadata.name().as_str(), "Bearer");
279        assert_eq!(metadata.kind(), ApiKeyLocation::default());
280        Ok(())
281    }
282}