Skip to main content

rustfs_iam/
oidc_state.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use moka::future::Cache;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19use tracing::warn;
20
21const OIDC_STATE_CAPACITY: u64 = 10_000;
22const OIDC_STATE_CAPACITY_WARNING: u64 = 9_000;
23const OIDC_STATE_CAPACITY_CRITICAL: u64 = 10_000;
24const OIDC_STATE_CAPACITY_LOG_INTERVAL_SECS: u64 = 60;
25
26/// Stores the PKCE verifier and nonce for an in-flight OIDC authorization flow.
27#[derive(Debug, Clone)]
28pub struct OidcAuthSession {
29    pub provider_id: String,
30    pub pkce_verifier: String,
31    pub nonce: String,
32    pub redirect_after: Option<String>,
33}
34
35/// Stores an ID token behind a one-time opaque handle so the console can trigger
36/// RP-initiated logout without persisting the raw token in browser storage.
37#[derive(Debug, Clone)]
38pub struct OidcLogoutSession {
39    pub provider_id: String,
40    pub id_token: String,
41}
42
43/// TTL cache for OIDC auth state (PKCE verifiers + nonces) during the authorization flow.
44/// Entries expire after 5 minutes and are single-use (removed on retrieval).
45#[derive(Clone)]
46pub struct OidcStateStore {
47    cache: Cache<String, OidcAuthSession>,
48    logout_cache: Cache<String, OidcLogoutSession>,
49    last_capacity_log_at: Arc<AtomicU64>,
50}
51
52impl OidcStateStore {
53    pub fn new() -> Self {
54        let cache = Cache::builder()
55            .max_capacity(OIDC_STATE_CAPACITY)
56            .time_to_live(Duration::from_secs(300)) // 5 minute TTL
57            .build();
58        let logout_cache = Cache::builder()
59            .max_capacity(OIDC_STATE_CAPACITY)
60            .time_to_live(Duration::from_secs(3600)) // 1 hour TTL to match console OIDC sessions
61            .build();
62        Self {
63            cache,
64            logout_cache,
65            last_capacity_log_at: Arc::new(AtomicU64::new(0)),
66        }
67    }
68
69    /// Store a new auth session keyed by the OAuth2 `state` parameter.
70    pub async fn insert(&self, state: String, session: OidcAuthSession) {
71        self.cache.insert(state, session).await;
72        let size = self.cache.entry_count();
73
74        if !Self::should_log_capacity_warning(&self.last_capacity_log_at) {
75            return;
76        }
77
78        if size >= OIDC_STATE_CAPACITY_CRITICAL {
79            self.cache.run_pending_tasks().await;
80            warn!("OIDC state store reached configured capacity ({size}/{OIDC_STATE_CAPACITY})");
81            return;
82        }
83
84        if size >= OIDC_STATE_CAPACITY_WARNING {
85            self.cache.run_pending_tasks().await;
86            warn!("OIDC state store approaching capacity ({size}/{OIDC_STATE_CAPACITY})");
87        }
88    }
89
90    fn now_unix_secs() -> u64 {
91        SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
92    }
93
94    fn should_log_capacity_warning(last_log_at: &AtomicU64) -> bool {
95        let now = Self::now_unix_secs();
96        let last = last_log_at.load(Ordering::Acquire);
97        if now.saturating_sub(last) < OIDC_STATE_CAPACITY_LOG_INTERVAL_SECS {
98            return false;
99        }
100        last_log_at
101            .compare_exchange(last, now, Ordering::AcqRel, Ordering::Acquire)
102            .is_ok()
103    }
104
105    /// Retrieve and remove an auth session (single-use). Returns None if expired or not found.
106    /// Uses `remove` which returns the value and removes it in a single operation.
107    pub async fn take(&self, state: &str) -> Option<OidcAuthSession> {
108        self.cache.remove(state).await
109    }
110
111    /// Check if a state key exists (without consuming it).
112    pub async fn contains(&self, state: &str) -> bool {
113        self.cache.get(state).await.is_some()
114    }
115
116    /// Store a new one-time logout session keyed by an opaque logout token.
117    pub async fn insert_logout(&self, token: String, session: OidcLogoutSession) {
118        self.logout_cache.insert(token, session).await;
119    }
120
121    /// Retrieve and remove a logout session (single-use). Returns None if expired or not found.
122    pub async fn take_logout(&self, token: &str) -> Option<OidcLogoutSession> {
123        self.logout_cache.remove(token).await
124    }
125
126    /// Check if a logout token exists (without consuming it).
127    pub async fn contains_logout(&self, token: &str) -> bool {
128        self.logout_cache.get(token).await.is_some()
129    }
130}
131
132impl Default for OidcStateStore {
133    fn default() -> Self {
134        Self::new()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use std::sync::Arc;
142    use tokio::sync::Barrier;
143
144    #[tokio::test]
145    async fn test_state_store_insert_and_take() {
146        let store = OidcStateStore::new();
147        let session = OidcAuthSession {
148            provider_id: "okta".to_string(),
149            pkce_verifier: "verifier123".to_string(),
150            nonce: "nonce456".to_string(),
151            redirect_after: Some("/dashboard".to_string()),
152        };
153
154        store.insert("state_abc".to_string(), session.clone()).await;
155        assert!(store.contains("state_abc").await);
156
157        let retrieved = store.take("state_abc").await;
158        assert!(retrieved.is_some());
159        let retrieved = retrieved.unwrap();
160        assert_eq!(retrieved.provider_id, "okta");
161        assert_eq!(retrieved.pkce_verifier, "verifier123");
162        assert_eq!(retrieved.nonce, "nonce456");
163        assert_eq!(retrieved.redirect_after, Some("/dashboard".to_string()));
164
165        // Single-use: second take should return None
166        assert!(store.take("state_abc").await.is_none());
167    }
168
169    #[tokio::test]
170    async fn test_state_store_missing_key() {
171        let store = OidcStateStore::new();
172        assert!(store.take("nonexistent").await.is_none());
173        assert!(!store.contains("nonexistent").await);
174    }
175
176    #[tokio::test]
177    async fn test_state_store_multiple_entries() {
178        let store = OidcStateStore::new();
179
180        for i in 0..5 {
181            let session = OidcAuthSession {
182                provider_id: format!("provider_{i}"),
183                pkce_verifier: format!("verifier_{i}"),
184                nonce: format!("nonce_{i}"),
185                redirect_after: None,
186            };
187            store.insert(format!("state_{i}"), session).await;
188        }
189
190        for i in 0..5 {
191            let retrieved = store.take(&format!("state_{i}")).await;
192            assert!(retrieved.is_some());
193            assert_eq!(retrieved.unwrap().provider_id, format!("provider_{i}"));
194        }
195
196        // All consumed
197        for i in 0..5 {
198            assert!(store.take(&format!("state_{i}")).await.is_none());
199        }
200    }
201
202    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
203    async fn auth_state_is_consumed_once_under_concurrent_take() {
204        let store = OidcStateStore::new();
205        store
206            .insert(
207                "state_once".to_string(),
208                OidcAuthSession {
209                    provider_id: "corp".to_string(),
210                    pkce_verifier: "verifier".to_string(),
211                    nonce: "nonce".to_string(),
212                    redirect_after: None,
213                },
214            )
215            .await;
216
217        let first_store = store.clone();
218        let second_store = store.clone();
219        let barrier = Arc::new(Barrier::new(3));
220        let first_barrier = Arc::clone(&barrier);
221        let first = tokio::spawn(async move {
222            first_barrier.wait().await;
223            first_store.take("state_once").await
224        });
225        let second_barrier = Arc::clone(&barrier);
226        let second = tokio::spawn(async move {
227            second_barrier.wait().await;
228            second_store.take("state_once").await
229        });
230        barrier.wait().await;
231        let first = first.await.expect("first state consumer should finish");
232        let second = second.await.expect("second state consumer should finish");
233
234        assert_eq!(first.is_some() as usize + second.is_some() as usize, 1);
235    }
236
237    #[tokio::test]
238    async fn test_logout_state_store_insert_and_take() {
239        let store = OidcStateStore::new();
240        let session = OidcLogoutSession {
241            provider_id: "okta".to_string(),
242            id_token: "jwt-token".to_string(),
243        };
244
245        store.insert_logout("logout_abc".to_string(), session.clone()).await;
246        assert!(store.contains_logout("logout_abc").await);
247
248        let retrieved = store.take_logout("logout_abc").await;
249        assert!(retrieved.is_some());
250        let retrieved = retrieved.unwrap();
251        assert_eq!(retrieved.provider_id, "okta");
252        assert_eq!(retrieved.id_token, "jwt-token");
253
254        assert!(store.take_logout("logout_abc").await.is_none());
255    }
256}