1use std::fmt;
4
5use zeroize::{Zeroize, ZeroizeOnDrop};
6
7pub(crate) const REDACTED: &str = "[REDACTED]";
9
10#[derive(Clone, Zeroize, ZeroizeOnDrop)]
27pub struct ApiKey(String);
28
29impl ApiKey {
30 pub fn new(mut key: String) -> Result<Self, InvalidApiKey> {
40 let trimmed = key.trim().to_owned();
41 key.zeroize();
42
43 let mut candidate = Self(trimmed);
44 if candidate.0.is_empty() {
45 return Err(InvalidApiKey::Empty);
46 }
47 if !candidate.0.bytes().all(|byte| byte.is_ascii_graphic()) {
48 candidate.zeroize();
49 return Err(InvalidApiKey::InvalidCharacters);
50 }
51 Ok(candidate)
52 }
53
54 #[must_use]
57 pub fn expose(&self) -> &str {
58 &self.0
59 }
60
61 pub(crate) fn scrub(&self, text: &str) -> String {
65 text.replace(self.0.as_str(), REDACTED)
66 }
67
68 pub(crate) fn scrub_bytes(&self, bytes: Vec<u8>) -> Vec<u8> {
71 let key = self.0.as_bytes();
72 if !bytes.windows(key.len()).any(|window| window == key) {
73 return bytes;
74 }
75 let mut scrubbed = Vec::with_capacity(bytes.len());
76 let mut rest = bytes.as_slice();
77 while !rest.is_empty() {
78 if rest.starts_with(key) {
79 scrubbed.extend_from_slice(REDACTED.as_bytes());
80 rest = rest.get(key.len()..).unwrap_or_default();
81 } else if let Some((first, tail)) = rest.split_first() {
82 scrubbed.push(*first);
83 rest = tail;
84 }
85 }
86 scrubbed
87 }
88}
89
90impl fmt::Debug for ApiKey {
91 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(formatter, "ApiKey({REDACTED})")
93 }
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
98#[non_exhaustive]
99pub enum InvalidApiKey {
100 #[error("the API key is empty")]
102 Empty,
103 #[error("the API key contains characters that cannot be sent in an HTTP header")]
105 InvalidCharacters,
106}
107
108#[cfg(test)]
109mod tests {
110 use super::{ApiKey, InvalidApiKey};
111
112 const SENTINEL: &str = "sentinel-key-0123456789";
113
114 #[test]
115 fn trims_the_whitespace_a_file_or_pipe_leaves_behind() {
116 let key = ApiKey::new(format!(" {SENTINEL}\r\n")).unwrap();
117
118 assert_eq!(key.expose(), SENTINEL);
119 }
120
121 #[test]
122 fn debug_never_shows_the_key() {
123 let key = ApiKey::new(SENTINEL.to_owned()).unwrap();
124
125 for rendered in [
126 format!("{key:?}"),
127 format!("{key:#?}"),
128 format!("{:?}", Some(&key)),
129 ] {
130 assert!(!rendered.contains(SENTINEL), "{rendered}");
131 assert!(rendered.contains("[REDACTED]"), "{rendered}");
132 }
133 }
134
135 #[test]
136 fn rejects_keys_that_cannot_be_sent_without_echoing_them() {
137 let cases = [
138 ("", InvalidApiKey::Empty),
139 (" \n\t", InvalidApiKey::Empty),
140 ("sentinel key", InvalidApiKey::InvalidCharacters),
141 ("sentinel\nkey", InvalidApiKey::InvalidCharacters),
142 ("sentinel-ключ", InvalidApiKey::InvalidCharacters),
143 ];
144
145 for (input, expected) in cases {
146 let error = ApiKey::new(input.to_owned()).unwrap_err();
147
148 assert_eq!(error, expected, "{input:?}");
149 assert!(!error.to_string().contains("sentinel"), "{error}");
150 assert!(!format!("{error:?}").contains("sentinel"), "{error:?}");
151 }
152 }
153
154 #[test]
155 fn scrubs_the_key_out_of_text_that_echoes_it() {
156 let key = ApiKey::new(SENTINEL.to_owned()).unwrap();
157
158 let scrubbed = key.scrub(&format!("bad header: Bearer {SENTINEL} ({SENTINEL})"));
159
160 assert_eq!(scrubbed, "bad header: Bearer [REDACTED] ([REDACTED])");
161 }
162
163 #[test]
164 fn scrubs_the_key_out_of_bytes_and_leaves_other_bytes_alone() {
165 let key = ApiKey::new(SENTINEL.to_owned()).unwrap();
166 let mut body = format!("{{\"echo\":\"Bearer {SENTINEL}\",\"k\":\"{SENTINEL}").into_bytes();
167 body.extend_from_slice(b"\xff\"}");
168
169 let scrubbed = key.scrub_bytes(body);
170
171 assert_eq!(
172 scrubbed,
173 b"{\"echo\":\"Bearer [REDACTED]\",\"k\":\"[REDACTED]\xff\"}".to_vec()
174 );
175 let untouched = b"no key here \xfe".to_vec();
176 assert_eq!(key.scrub_bytes(untouched.clone()), untouched);
177 }
178}