axum_oidc_layer/cache/mod.rs
1//! Caching functionality for OIDC authentication.
2//!
3//! This module provides caching traits and type-safe cache key wrappers
4//! to efficiently store OIDC configuration, JWKS keys, and token validation results.
5
6use std::{collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, time::Duration};
7
8pub mod memory;
9
10pub use memory::InMemoryCache;
11
12/// Trait for caching `JWKS` keys and `OIDC` configuration.
13///
14/// This trait allows users to implement custom caching strategies,
15/// such as Redis, database, or custom in-memory implementations.
16pub trait JwksCache: Send + Sync {
17 /// Retrieves a cached value by key.
18 /// Returns `None` if the key doesn't exist or has expired.
19 fn get(&self, key: &str) -> Option<String>;
20
21 /// Stores a value in the cache with the specified TTL.
22 fn set(&self, key: &str, value: String, ttl: Duration);
23}
24
25/// Type-safe cache key for JWT tokens.
26///
27/// Prevents accidentally mixing token cache keys with other cache key types.
28#[derive(Debug, Clone, PartialEq, Eq, Hash)]
29pub struct TokenCacheKey(String);
30
31impl TokenCacheKey {
32 /// Creates a cache key from a JWT token by hashing it.
33 #[must_use]
34 pub fn from_token(token: &str) -> Self {
35 let mut hasher = DefaultHasher::new();
36 token.hash(&mut hasher);
37 Self(format!("token:{}", hasher.finish()))
38 }
39
40 /// Returns the cache key as a string.
41 #[must_use]
42 pub fn as_str(&self) -> &str {
43 &self.0
44 }
45}
46
47/// Type-safe cache key for OIDC configuration.
48///
49/// Prevents accidentally mixing config cache keys with other cache key types.
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub struct ConfigCacheKey(String);
52
53impl ConfigCacheKey {
54 /// Creates a cache key for OIDC configuration.
55 #[must_use]
56 pub fn from_url(url: &str) -> Self {
57 Self(format!("config:{url}"))
58 }
59
60 /// Returns the cache key as a string.
61 #[must_use]
62 pub fn as_str(&self) -> &str {
63 &self.0
64 }
65}
66
67/// Type-safe cache key for individual JWK keys.
68///
69/// Prevents accidentally mixing JWK cache keys with other cache key types.
70#[derive(Debug, Clone, PartialEq, Eq, Hash)]
71pub struct JwkCacheKey(String);
72
73impl JwkCacheKey {
74 /// Creates a cache key for a specific JWK.
75 #[must_use]
76 pub fn from_jwks_uri_and_kid(jwks_uri: &str, kid: &str) -> Self {
77 Self(format!("jwk:{jwks_uri}:{kid}"))
78 }
79
80 /// Returns the cache key as a string.
81 #[must_use]
82 pub fn as_str(&self) -> &str {
83 &self.0
84 }
85}