stateknot_integrations/
credential.rs1use std::{fmt, sync::Arc};
5
6use stateknot_core::{BoxFuture, ModelContext};
7use thiserror::Error;
8use zeroize::Zeroizing;
9
10#[derive(Clone)]
12pub struct ApiKey(Zeroizing<String>);
13
14impl ApiKey {
15 pub const MAX_BYTES: usize = 8192;
17
18 pub fn new(value: impl Into<String>) -> Result<Self, ApiKeyError> {
25 let value = Zeroizing::new(value.into());
26 if value.is_empty() {
27 return Err(ApiKeyError::Empty);
28 }
29 if value.len() > Self::MAX_BYTES {
30 return Err(ApiKeyError::TooLong {
31 maximum: Self::MAX_BYTES,
32 actual: value.len(),
33 });
34 }
35 if value.trim() != value.as_str() {
36 return Err(ApiKeyError::WhitespacePadded);
37 }
38 if let Some((index, _)) = value
39 .bytes()
40 .enumerate()
41 .find(|(_, byte)| !matches!(byte, b'!'..=b'~'))
42 {
43 return Err(ApiKeyError::InvalidByte { index });
44 }
45 Ok(Self(value))
46 }
47
48 pub(crate) fn expose_secret(&self) -> &str {
49 self.0.as_str()
50 }
51}
52
53impl fmt::Debug for ApiKey {
54 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55 formatter.write_str("ApiKey([REDACTED])")
56 }
57}
58
59#[derive(Clone, Debug, Eq, Error, PartialEq)]
61#[non_exhaustive]
62pub enum ApiKeyError {
63 #[error("provider API key must not be empty")]
65 Empty,
66 #[error("provider API key is {actual} bytes; maximum is {maximum}")]
68 TooLong {
69 maximum: usize,
71 actual: usize,
73 },
74 #[error("provider API key must not have surrounding whitespace")]
76 WhitespacePadded,
77 #[error("provider API key contains an invalid byte at offset {index}")]
79 InvalidByte {
80 index: usize,
82 },
83}
84
85#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
87#[non_exhaustive]
88pub enum ApiKeyResolutionError {
89 #[error("provider credential source is unavailable")]
91 Unavailable,
92 #[error("provider credential access was denied")]
94 PermissionDenied,
95}
96
97pub trait ApiKeyProvider: Send + Sync + 'static {
103 fn resolve(
105 &self,
106 context: &ModelContext,
107 ) -> BoxFuture<'_, Result<ApiKey, ApiKeyResolutionError>>;
108}
109
110#[derive(Clone)]
112pub struct StaticApiKey {
113 key: Arc<ApiKey>,
114}
115
116impl StaticApiKey {
117 #[must_use]
119 pub fn new(key: ApiKey) -> Self {
120 Self { key: Arc::new(key) }
121 }
122}
123
124impl fmt::Debug for StaticApiKey {
125 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126 formatter.write_str("StaticApiKey([REDACTED])")
127 }
128}
129
130impl ApiKeyProvider for StaticApiKey {
131 fn resolve(
132 &self,
133 _context: &ModelContext,
134 ) -> BoxFuture<'_, Result<ApiKey, ApiKeyResolutionError>> {
135 let key = self.key.as_ref().clone();
136 Box::pin(async move { Ok(key) })
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn credentials_are_header_safe_and_always_redacted() {
146 let secret = "sk-production-secret";
147 let key = ApiKey::new(secret).unwrap();
148 assert_eq!(key.expose_secret(), secret);
149 assert!(!format!("{key:?}").contains(secret));
150 assert!(!format!("{:?}", StaticApiKey::new(key)).contains(secret));
151
152 assert!(matches!(ApiKey::new(""), Err(ApiKeyError::Empty)));
153 assert!(matches!(
154 ApiKey::new(" padded"),
155 Err(ApiKeyError::WhitespacePadded)
156 ));
157 assert!(matches!(
158 ApiKey::new("line\nbreak"),
159 Err(ApiKeyError::InvalidByte { .. })
160 ));
161 }
162}