Skip to main content

stateknot_integrations/
credential.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{fmt, sync::Arc};
5
6use stateknot_core::{BoxFuture, ModelContext};
7use thiserror::Error;
8use zeroize::Zeroizing;
9
10/// A validated provider credential whose storage is zeroized on final drop.
11#[derive(Clone)]
12pub struct ApiKey(Zeroizing<String>);
13
14impl ApiKey {
15    /// Maximum accepted credential length in bytes.
16    pub const MAX_BYTES: usize = 8192;
17
18    /// Validates and takes ownership of a provider credential.
19    ///
20    /// # Errors
21    ///
22    /// Returns [`ApiKeyError`] for empty, oversized, whitespace-padded, or
23    /// header-unsafe values.
24    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/// Invalid provider credential material.
60#[derive(Clone, Debug, Eq, Error, PartialEq)]
61#[non_exhaustive]
62pub enum ApiKeyError {
63    /// The credential was empty.
64    #[error("provider API key must not be empty")]
65    Empty,
66    /// The credential exceeded the hard resource ceiling.
67    #[error("provider API key is {actual} bytes; maximum is {maximum}")]
68    TooLong {
69        /// Hard maximum.
70        maximum: usize,
71        /// Observed bytes.
72        actual: usize,
73    },
74    /// Trimming would change the credential.
75    #[error("provider API key must not have surrounding whitespace")]
76    WhitespacePadded,
77    /// A byte could not be represented safely in an HTTP header.
78    #[error("provider API key contains an invalid byte at offset {index}")]
79    InvalidByte {
80        /// Zero-based invalid byte offset.
81        index: usize,
82    },
83}
84
85/// Public-safe classification returned by a dynamic credential source.
86#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
87#[non_exhaustive]
88pub enum ApiKeyResolutionError {
89    /// The scoped secret backend was temporarily unavailable.
90    #[error("provider credential source is unavailable")]
91    Unavailable,
92    /// Policy refused credential access for this attempt context.
93    #[error("provider credential access was denied")]
94    PermissionDenied,
95}
96
97/// Attempt-scoped provider credential source.
98///
99/// Implementations should resolve secret handles after durable attempt claim,
100/// apply tenant policy using `context`, and avoid retaining plaintext longer
101/// than necessary. Returned values are never formatted by `StateKnot`.
102pub trait ApiKeyProvider: Send + Sync + 'static {
103    /// Resolves one credential for the exact attempt.
104    fn resolve(
105        &self,
106        context: &ModelContext,
107    ) -> BoxFuture<'_, Result<ApiKey, ApiKeyResolutionError>>;
108}
109
110/// Immutable in-memory credential provider for controlled deployments.
111#[derive(Clone)]
112pub struct StaticApiKey {
113    key: Arc<ApiKey>,
114}
115
116impl StaticApiKey {
117    /// Wraps one validated key.
118    #[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}