Skip to main content

jev_client/
secret.rs

1//! The API key, held so that it is hard to leak by accident.
2
3use std::fmt;
4
5use zeroize::{Zeroize, ZeroizeOnDrop};
6
7/// What is shown in place of a secret wherever one could otherwise be printed.
8pub(crate) const REDACTED: &str = "[REDACTED]";
9
10/// A TypeSafe API key.
11///
12/// The key is wiped from memory when the value is dropped, and nothing in this crate prints it:
13/// `Debug` shows a placeholder, and there is deliberately no `Display`, `Serialize` or `PartialEq`.
14/// The only way to read it is [`ApiKey::expose`], which keeps every use easy to find and review.
15///
16/// Wiping is best effort. The HTTP stack keeps its own copy of the `Authorization` header while a
17/// transport is alive, and that copy is outside this type's control.
18///
19/// ```
20/// use jev_client::ApiKey;
21///
22/// let key = ApiKey::new(String::from("example-key\n")).unwrap();
23/// assert_eq!(key.expose(), "example-key");
24/// assert_eq!(format!("{key:?}"), "ApiKey([REDACTED])");
25/// ```
26#[derive(Clone, Zeroize, ZeroizeOnDrop)]
27pub struct ApiKey(String);
28
29impl ApiKey {
30    /// Wraps a key, trimming surrounding whitespace such as the newline a file or a pipe leaves.
31    ///
32    /// The string is taken by value so that the caller's copy is consumed; the original buffer is
33    /// wiped before this returns.
34    ///
35    /// # Errors
36    ///
37    /// Fails when the key is empty, or contains anything other than visible ASCII characters,
38    /// which could not be sent in an HTTP header. The error never contains the key.
39    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    /// The key itself. Call this only at the point where the key is handed to the HTTP stack or
55    /// to a credential store, and never pass the result to a log, an error or a formatter.
56    #[must_use]
57    pub fn expose(&self) -> &str {
58        &self.0
59    }
60
61    /// Replaces every occurrence of the key in `text` with a placeholder.
62    ///
63    /// Used on text that came from the server, which could echo a header back in an error message.
64    pub(crate) fn scrub(&self, text: &str) -> String {
65        text.replace(self.0.as_str(), REDACTED)
66    }
67
68    /// [`ApiKey::scrub`] for a body that may not be UTF-8. Bytes are returned unchanged unless the
69    /// key is among them.
70    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/// Why a string was rejected as an API key. The message never contains the key.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
98#[non_exhaustive]
99pub enum InvalidApiKey {
100    /// The key was empty, or only whitespace.
101    #[error("the API key is empty")]
102    Empty,
103    /// The key held a space, a control character or a non-ASCII character.
104    #[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}