Skip to main content

wabot_addon_auth_api_key/
lib.rs

1//! # wabot-addon-auth-api-key
2//!
3//! API-key credentials and the guard that checks them. Port of
4//! `wabot-ts/src/addon/auth/api-key` (`ApiKey`, `ApiKeyRepository`,
5//! `ApiKeyGuardMiddleware`).
6//!
7//! ```ignore
8//! let keys = Arc::new(InMemoryApiKeyRepository::new());
9//! register_api_key_repository(&c, keys.clone());
10//! register_singletons!(&c, ApiKeyGuard);
11//!
12//! // Mint one — the secret is returned exactly once.
13//! let issued = keys.generate("ci-deploy", json!({ "sub": "svc-ci" }), Default::default()).await?;
14//! println!("give this to the caller: {}", issued.secret);
15//! ```
16//!
17//! Callers then send `Authorization: Api-Key sk_…`, and the guard fills
18//! the request's [`Auth`] with the key's stored claims.
19//!
20//! ## How secrets are stored
21//!
22//! Only a SHA-256 hash is persisted, so a database leak doesn't hand
23//! over working credentials, and the comparison is constant-time so a
24//! caller can't recover a hash byte-by-byte from response timing. The
25//! plaintext exists only in the [`IssuedApiKey`] returned by
26//! [`ApiKeyRepository::generate`] — there is deliberately no way to
27//! read it back later.
28
29/// Socket.IO handshake guard. Behind the `socket` feature so a
30/// REST-only app doesn't compile socketioxide.
31#[cfg(feature = "socket")]
32pub mod handshake;
33#[cfg(feature = "socket")]
34pub use handshake::ApiKeyHandshakeGuard;
35
36use std::collections::HashMap;
37use std::sync::Arc;
38
39use async_trait::async_trait;
40use parking_lot::Mutex;
41use serde::{Deserialize, Serialize};
42use sha2::{Digest, Sha256};
43use subtle::ConstantTimeEq;
44use thiserror::Error;
45
46use wabot_core::audit::{audit_actor_resolver, set_audit_actor};
47use wabot_core::auth::Auth;
48use wabot_core::entity::{Entity, EntityData, EntityFields};
49use wabot_core::injection::{Container, IsSingleton};
50use wabot_feature_rest_controller::{
51    axum::http::request::Parts, Middleware, RestError, RestResult,
52};
53
54/// Prefix every secret carries, matching the TS `ApiKey.PREFIX`.
55pub const SECRET_PREFIX: &str = "sk_";
56
57#[derive(Debug, Error)]
58pub enum ApiKeyError {
59    #[error("this API key already has a secret")]
60    AlreadyIssued,
61    #[error("storage error: {0}")]
62    Storage(String),
63}
64
65/// Stored form of a key. The secret itself is never in here.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67#[serde(rename_all = "camelCase")]
68pub struct ApiKeyData {
69    #[serde(flatten)]
70    pub base: EntityData,
71    /// Human label, so a key can be identified and revoked.
72    pub name: String,
73    /// SHA-256 of the secret, hex-encoded.
74    #[serde(skip_serializing_if = "Option::is_none", default)]
75    pub secret_hash: Option<String>,
76    /// Claims assigned to [`Auth`] when this key authenticates.
77    pub auth_info: serde_json::Value,
78    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
79    pub metadata: HashMap<String, String>,
80    /// Unix millis after which the key stops working. `None` = never.
81    #[serde(skip_serializing_if = "Option::is_none", default)]
82    pub expires_at: Option<i64>,
83    /// Unix millis the key was revoked at. `None` = active.
84    #[serde(skip_serializing_if = "Option::is_none", default)]
85    pub revoked_at: Option<i64>,
86}
87
88impl EntityFields for ApiKeyData {
89    fn entity(&self) -> &EntityData {
90        &self.base
91    }
92    fn entity_mut(&mut self) -> &mut EntityData {
93        &mut self.base
94    }
95}
96
97pub type ApiKey = Entity<ApiKeyData>;
98
99/// A freshly minted key. `secret` is the only time the plaintext
100/// exists — store the [`ApiKey`], hand the secret to the caller.
101#[derive(Debug, Clone)]
102pub struct IssuedApiKey {
103    pub api_key: ApiKey,
104    pub secret: String,
105}
106
107/// SHA-256, hex-encoded. Matches TS's `ApiKey.hashSecret`.
108pub fn hash_secret(secret: &str) -> String {
109    hex::encode(Sha256::digest(secret.as_bytes()))
110}
111
112/// Mint a new key with a random secret.
113pub fn new_api_key(
114    name: impl Into<String>,
115    auth_info: serde_json::Value,
116    metadata: HashMap<String, String>,
117) -> IssuedApiKey {
118    let secret = generate_secret();
119    let api_key = Entity::create(ApiKeyData {
120        base: EntityData::default(),
121        name: name.into(),
122        secret_hash: Some(hash_secret(&secret)),
123        auth_info,
124        metadata,
125        expires_at: None,
126        revoked_at: None,
127    });
128    IssuedApiKey { api_key, secret }
129}
130
131/// `sk_` + 32 bytes of CSPRNG output, hex-encoded.
132pub fn generate_secret() -> String {
133    format!("{SECRET_PREFIX}{}", wabot_core::random::hex(32))
134}
135
136/// Constant-time check of `secret` against the stored hash.
137///
138/// Constant-time because a byte-by-byte early return leaks how much of
139/// a guessed hash was right, which is enough to reconstruct it.
140pub fn is_valid_secret(key: &ApiKey, secret: &str) -> bool {
141    if !secret.starts_with(SECRET_PREFIX) {
142        return false;
143    }
144    let Some(stored) = &key.data().secret_hash else {
145        return false;
146    };
147    let (Ok(stored), Ok(candidate)) = (hex::decode(stored), hex::decode(hash_secret(secret)))
148    else {
149        return false;
150    };
151    stored.len() == candidate.len() && bool::from(stored.ct_eq(&candidate))
152}
153
154/// True when the key is neither revoked nor past its expiry.
155pub fn is_active(key: &ApiKey, now_ms: i64) -> bool {
156    let data = key.data();
157    data.revoked_at.is_none() && data.expires_at.is_none_or(|at| at > now_ms)
158}
159
160/// Storage for API keys. Implement against a real database; the
161/// in-memory one below is for tests and single-process deployments.
162#[async_trait]
163pub trait ApiKeyRepository: Send + Sync {
164    async fn find_by_hash(&self, secret_hash: &str) -> Result<Option<ApiKey>, ApiKeyError>;
165    async fn create(&self, key: &ApiKey) -> Result<(), ApiKeyError>;
166    async fn update(&self, key: &ApiKey) -> Result<(), ApiKeyError>;
167
168    /// Look a secret up and return its claims, or `None` when the key
169    /// is unknown, revoked, expired, or the secret doesn't match.
170    ///
171    /// The lookup is by hash, so an attacker with database read access
172    /// still can't authenticate without the plaintext.
173    async fn find_and_validate(
174        &self,
175        secret: &str,
176    ) -> Result<Option<serde_json::Value>, ApiKeyError> {
177        let Some(key) = self.find_by_hash(&hash_secret(secret)).await? else {
178            return Ok(None);
179        };
180        if !is_valid_secret(&key, secret) || !is_active(&key, chrono::Utc::now().timestamp_millis())
181        {
182            return Ok(None);
183        }
184        Ok(Some(key.data().auth_info.clone()))
185    }
186
187    /// Mint, persist, and return the plaintext secret once.
188    async fn generate(
189        &self,
190        name: &str,
191        auth_info: serde_json::Value,
192        metadata: HashMap<String, String>,
193    ) -> Result<IssuedApiKey, ApiKeyError> {
194        let issued = new_api_key(name, auth_info, metadata);
195        self.create(&issued.api_key).await?;
196        Ok(issued)
197    }
198}
199
200/// Container shim, same reasoning as the async feature's repository
201/// shims: a bare trait object can't be a container key.
202pub struct DynApiKeyRepository(pub Arc<dyn ApiKeyRepository>);
203
204pub fn register_api_key_repository(container: &Container, repo: Arc<dyn ApiKeyRepository>) {
205    container.register_instance::<DynApiKeyRepository>(Arc::new(DynApiKeyRepository(repo)));
206}
207
208/// In-memory store, indexed by secret hash.
209#[derive(Default)]
210pub struct InMemoryApiKeyRepository {
211    by_id: Mutex<HashMap<String, ApiKey>>,
212}
213
214impl InMemoryApiKeyRepository {
215    pub fn new() -> Self {
216        Self::default()
217    }
218
219    /// Revoke a key by id, so later requests with its secret fail.
220    pub fn revoke(&self, id: &str) {
221        if let Some(key) = self.by_id.lock().get_mut(id) {
222            key.update(|d| d.revoked_at = Some(chrono::Utc::now().timestamp_millis()));
223        }
224    }
225}
226
227#[async_trait]
228impl ApiKeyRepository for InMemoryApiKeyRepository {
229    async fn find_by_hash(&self, secret_hash: &str) -> Result<Option<ApiKey>, ApiKeyError> {
230        Ok(self
231            .by_id
232            .lock()
233            .values()
234            .find(|k| k.data().secret_hash.as_deref() == Some(secret_hash))
235            .cloned())
236    }
237
238    async fn create(&self, key: &ApiKey) -> Result<(), ApiKeyError> {
239        self.by_id.lock().insert(key.id().to_string(), key.clone());
240        Ok(())
241    }
242
243    async fn update(&self, key: &ApiKey) -> Result<(), ApiKeyError> {
244        self.by_id.lock().insert(key.id().to_string(), key.clone());
245        Ok(())
246    }
247}
248
249impl IsSingleton for InMemoryApiKeyRepository {
250    fn register_in(c: &Container) {
251        c.register_singleton_factory::<InMemoryApiKeyRepository, _>(|_| {
252            Arc::new(InMemoryApiKeyRepository::new())
253        });
254    }
255}
256
257/// Guard for `Authorization: Api-Key sk_…`.
258pub struct ApiKeyGuard {
259    repository: Arc<dyn ApiKeyRepository>,
260}
261
262impl ApiKeyGuard {
263    pub fn new(repository: Arc<dyn ApiKeyRepository>) -> Self {
264        Self { repository }
265    }
266
267    /// Pull the secret out of the header. A present-but-wrong scheme is
268    /// an error rather than a miss, so a client using the wrong scheme
269    /// gets told instead of a bare 401.
270    fn extract(parts: &Parts) -> RestResult<String> {
271        let header = parts
272            .headers
273            .get("authorization")
274            .ok_or_else(|| RestError::Unauthorized("Authorization header not available".into()))?
275            .to_str()
276            .map_err(|_| RestError::Unauthorized("Invalid Authorization header".into()))?;
277
278        let mut split = header.split(' ');
279        let scheme = split.next().unwrap_or_default();
280        let secret = split.next().unwrap_or_default();
281        if !scheme.eq_ignore_ascii_case("api-key") || secret.is_empty() || split.next().is_some() {
282            return Err(RestError::Unauthorized(
283                "Authorization must be: Api-Key <secret>".into(),
284            ));
285        }
286        Ok(secret.to_string())
287    }
288}
289
290#[async_trait]
291impl Middleware for ApiKeyGuard {
292    async fn handle(&self, parts: &Parts, container: &Container) -> RestResult<()> {
293        let secret = Self::extract(parts)?;
294
295        let auth_info = self
296            .repository
297            .find_and_validate(&secret)
298            .await
299            .map_err(|e| {
300                // A storage failure is not the caller's fault, and
301                // reporting it as 401 would send them into a retry loop
302                // against a broken database.
303                tracing::error!(error = %e, "api key lookup failed");
304                RestError::Internal("api key lookup failed".into())
305            })?
306            .ok_or_else(|| RestError::Unauthorized("Invalid key".into()))?;
307
308        // Same attribution as the JWT guard: the key's stored claims
309        // go through the app's resolver.
310        set_audit_actor(audit_actor_resolver(container).from_auth(&auth_info));
311
312        Auth::of(container)
313            .assign(auth_info)
314            .map_err(|e| RestError::Unauthorized(e.to_string()))
315    }
316}
317
318impl IsSingleton for ApiKeyGuard {
319    fn register_in(c: &Container) {
320        // So a controller holding `Arc<Auth>` still resolves on
321        // endpoints this guard doesn't cover.
322        Auth::register_default(c);
323        c.register_singleton_factory::<ApiKeyGuard, _>(|c2| {
324            let repo: Arc<DynApiKeyRepository> = c2.resolve();
325            Arc::new(ApiKeyGuard::new(repo.0.clone()))
326        });
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use serde_json::json;
334    use wabot_feature_rest_controller::axum::http::Request;
335
336    fn parts_with(header: Option<&str>) -> Parts {
337        let mut builder = Request::builder().uri("/");
338        if let Some(value) = header {
339            builder = builder.header("authorization", value);
340        }
341        builder.body(()).unwrap().into_parts().0
342    }
343
344    async fn guarded(
345        repo: Arc<InMemoryApiKeyRepository>,
346        header: Option<&str>,
347    ) -> RestResult<Arc<Auth>> {
348        let container = Container::new().create_child();
349        ApiKeyGuard::new(repo)
350            .handle(&parts_with(header), &container)
351            .await?;
352        Ok(Auth::of(&container))
353    }
354
355    async fn repo_with_key() -> (Arc<InMemoryApiKeyRepository>, IssuedApiKey) {
356        let repo = Arc::new(InMemoryApiKeyRepository::new());
357        let issued = repo
358            .generate(
359                "ci",
360                json!({ "sub": "svc-ci", "scope": "deploy" }),
361                HashMap::new(),
362            )
363            .await
364            .unwrap();
365        (repo, issued)
366    }
367
368    #[test]
369    fn secrets_are_prefixed_and_unguessable() {
370        let a = generate_secret();
371        let b = generate_secret();
372        assert!(a.starts_with(SECRET_PREFIX));
373        assert_eq!(a.len(), SECRET_PREFIX.len() + 64, "32 bytes as hex");
374        assert_ne!(a, b);
375    }
376
377    #[test]
378    fn only_the_hash_is_stored() {
379        let issued = new_api_key("ci", json!({}), HashMap::new());
380        let stored = serde_json::to_string(issued.api_key.data()).unwrap();
381        assert!(
382            !stored.contains(&issued.secret),
383            "the plaintext secret must never be persisted"
384        );
385        assert!(stored.contains(&hash_secret(&issued.secret)));
386    }
387
388    #[test]
389    fn validation_accepts_only_the_real_secret() {
390        let issued = new_api_key("ci", json!({}), HashMap::new());
391        assert!(is_valid_secret(&issued.api_key, &issued.secret));
392        assert!(!is_valid_secret(&issued.api_key, "sk_deadbeef"));
393        assert!(
394            !is_valid_secret(&issued.api_key, &issued.secret.replace("sk_", "")),
395            "the prefix is part of the credential"
396        );
397    }
398
399    #[tokio::test]
400    async fn a_valid_key_authenticates_and_carries_its_claims() {
401        let (repo, issued) = repo_with_key().await;
402        let header = format!("Api-Key {}", issued.secret);
403        let auth = guarded(repo, Some(&header)).await.unwrap();
404
405        let claims = auth.require().unwrap();
406        assert_eq!(claims["sub"], "svc-ci");
407        assert_eq!(claims["scope"], "deploy");
408    }
409
410    #[tokio::test]
411    async fn the_scheme_is_case_insensitive() {
412        let (repo, issued) = repo_with_key().await;
413        let header = format!("api-key {}", issued.secret);
414        assert!(guarded(repo, Some(&header)).await.is_ok());
415    }
416
417    #[tokio::test]
418    async fn an_unknown_secret_is_rejected() {
419        let (repo, _) = repo_with_key().await;
420        let header = format!("Api-Key {}", generate_secret());
421        assert!(matches!(
422            guarded(repo, Some(&header)).await,
423            Err(RestError::Unauthorized(_))
424        ));
425    }
426
427    #[tokio::test]
428    async fn a_revoked_key_stops_working() {
429        let (repo, issued) = repo_with_key().await;
430        let header = format!("Api-Key {}", issued.secret);
431        assert!(guarded(repo.clone(), Some(&header)).await.is_ok());
432
433        repo.revoke(issued.api_key.id());
434        assert!(
435            matches!(
436                guarded(repo, Some(&header)).await,
437                Err(RestError::Unauthorized(_))
438            ),
439            "revocation must take effect immediately"
440        );
441    }
442
443    #[tokio::test]
444    async fn an_expired_key_stops_working() {
445        let repo = Arc::new(InMemoryApiKeyRepository::new());
446        let mut issued = new_api_key("temp", json!({ "sub": "svc" }), HashMap::new());
447        issued
448            .api_key
449            .update(|d| d.expires_at = Some(chrono::Utc::now().timestamp_millis() - 1_000));
450        repo.create(&issued.api_key).await.unwrap();
451
452        let header = format!("Api-Key {}", issued.secret);
453        assert!(matches!(
454            guarded(repo, Some(&header)).await,
455            Err(RestError::Unauthorized(_))
456        ));
457    }
458
459    #[tokio::test]
460    async fn the_wrong_scheme_and_no_header_are_both_refused() {
461        let (repo, issued) = repo_with_key().await;
462        let bearer = format!("Bearer {}", issued.secret);
463
464        assert!(matches!(
465            guarded(repo.clone(), Some(&bearer)).await,
466            Err(RestError::Unauthorized(_))
467        ));
468        assert!(matches!(
469            guarded(repo.clone(), Some("Api-Key")).await,
470            Err(RestError::Unauthorized(_))
471        ));
472        assert!(matches!(
473            guarded(repo, None).await,
474            Err(RestError::Unauthorized(_))
475        ));
476    }
477
478    #[tokio::test]
479    async fn generate_returns_the_secret_exactly_once() {
480        let (repo, issued) = repo_with_key().await;
481        // The stored copy has no way to give the plaintext back.
482        let stored = repo
483            .find_by_hash(&hash_secret(&issued.secret))
484            .await
485            .unwrap()
486            .unwrap();
487        assert_eq!(stored.id(), issued.api_key.id());
488        assert_eq!(stored.data().name, "ci");
489        assert!(stored.data().secret_hash.is_some());
490    }
491}