use std::{fmt, sync::Arc};
use stateknot_core::{BoxFuture, ModelContext};
use thiserror::Error;
use zeroize::Zeroizing;
#[derive(Clone)]
pub struct ApiKey(Zeroizing<String>);
impl ApiKey {
pub const MAX_BYTES: usize = 8192;
pub fn new(value: impl Into<String>) -> Result<Self, ApiKeyError> {
let value = Zeroizing::new(value.into());
if value.is_empty() {
return Err(ApiKeyError::Empty);
}
if value.len() > Self::MAX_BYTES {
return Err(ApiKeyError::TooLong {
maximum: Self::MAX_BYTES,
actual: value.len(),
});
}
if value.trim() != value.as_str() {
return Err(ApiKeyError::WhitespacePadded);
}
if let Some((index, _)) = value
.bytes()
.enumerate()
.find(|(_, byte)| !matches!(byte, b'!'..=b'~'))
{
return Err(ApiKeyError::InvalidByte { index });
}
Ok(Self(value))
}
pub(crate) fn expose_secret(&self) -> &str {
self.0.as_str()
}
}
impl fmt::Debug for ApiKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ApiKey([REDACTED])")
}
}
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ApiKeyError {
#[error("provider API key must not be empty")]
Empty,
#[error("provider API key is {actual} bytes; maximum is {maximum}")]
TooLong {
maximum: usize,
actual: usize,
},
#[error("provider API key must not have surrounding whitespace")]
WhitespacePadded,
#[error("provider API key contains an invalid byte at offset {index}")]
InvalidByte {
index: usize,
},
}
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum ApiKeyResolutionError {
#[error("provider credential source is unavailable")]
Unavailable,
#[error("provider credential access was denied")]
PermissionDenied,
}
pub trait ApiKeyProvider: Send + Sync + 'static {
fn resolve(
&self,
context: &ModelContext,
) -> BoxFuture<'_, Result<ApiKey, ApiKeyResolutionError>>;
}
#[derive(Clone)]
pub struct StaticApiKey {
key: Arc<ApiKey>,
}
impl StaticApiKey {
#[must_use]
pub fn new(key: ApiKey) -> Self {
Self { key: Arc::new(key) }
}
}
impl fmt::Debug for StaticApiKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("StaticApiKey([REDACTED])")
}
}
impl ApiKeyProvider for StaticApiKey {
fn resolve(
&self,
_context: &ModelContext,
) -> BoxFuture<'_, Result<ApiKey, ApiKeyResolutionError>> {
let key = self.key.as_ref().clone();
Box::pin(async move { Ok(key) })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn credentials_are_header_safe_and_always_redacted() {
let secret = "sk-production-secret";
let key = ApiKey::new(secret).unwrap();
assert_eq!(key.expose_secret(), secret);
assert!(!format!("{key:?}").contains(secret));
assert!(!format!("{:?}", StaticApiKey::new(key)).contains(secret));
assert!(matches!(ApiKey::new(""), Err(ApiKeyError::Empty)));
assert!(matches!(
ApiKey::new(" padded"),
Err(ApiKeyError::WhitespacePadded)
));
assert!(matches!(
ApiKey::new("line\nbreak"),
Err(ApiKeyError::InvalidByte { .. })
));
}
}