1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10 Empty,
12 Invalid,
14 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 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 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62 Self::new(value)
63 }
64
65 #[must_use]
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 #[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#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
113pub struct ApiKey(String);
114
115impl ApiKey {
116 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 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
131 Self::new(value)
132 }
133
134 #[must_use]
136 pub fn as_str(&self) -> &str {
137 &self.0
138 }
139
140 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
179pub enum ApiKeyStatus {
180 Active,
182 Revoked,
184 Expired,
186 Suspended,
188}
189
190impl ApiKeyStatus {
191 #[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#[derive(Clone, Debug, Eq, PartialEq)]
236pub struct PrimitiveMetadata {
237 name: ApiKeyId,
238 kind: ApiKeyStatus,
239}
240
241impl PrimitiveMetadata {
242 #[must_use]
244 pub const fn new(name: ApiKeyId, kind: ApiKeyStatus) -> Self {
245 Self { name, kind }
246 }
247
248 #[must_use]
250 pub const fn name(&self) -> &ApiKeyId {
251 &self.name
252 }
253
254 #[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 #[must_use]
270 pub fn redacted(&self) -> String {
271 redact_api_key(self.as_str())
272 }
273}
274
275#[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#[derive(Clone, Debug, Eq, PartialEq)]
289pub struct ApiKeyMetadata {
290 id: ApiKeyId,
291 prefix: ApiKeyPrefix,
292 status: ApiKeyStatus,
293}
294
295impl ApiKeyMetadata {
296 #[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}