Skip to main content

hyprstream_workers/events/
token_manager.rs

1//! JWT lifecycle manager for event scope authorization.
2//!
3//! Manages token issuance and automatic refresh for event publishers and subscribers
4//! that need to authenticate with PolicyService for group key operations.
5
6use std::sync::Arc;
7use std::time::Duration;
8
9use tokio::sync::RwLock;
10use tokio::task::JoinHandle;
11use tokio_util::sync::CancellationToken;
12
13/// Manages JWT lifecycle for event scope authorization.
14///
15/// Automatically refreshes tokens before expiry to maintain continuous access
16/// to PolicyService event prefix operations.
17pub struct EventTokenManager {
18    /// Current valid token.
19    current_token: Arc<RwLock<String>>,
20    /// Scope string for token issuance (e.g., "publish:events:worker.*").
21    scope: String,
22    /// Audience for token issuance (e.g., "events").
23    audience: String,
24    /// Token TTL in seconds.
25    ttl_secs: u64,
26    /// Background refresh task handle.
27    refresh_handle: Option<JoinHandle<()>>,
28    /// Cancellation token for the refresh loop.
29    cancel: CancellationToken,
30}
31
32impl EventTokenManager {
33    /// Create a new EventTokenManager with an initial token.
34    pub fn new(initial_token: String, scope: String, audience: String, ttl_secs: u64) -> Self {
35        Self {
36            current_token: Arc::new(RwLock::new(initial_token)),
37            scope,
38            audience,
39            ttl_secs,
40            refresh_handle: None,
41            cancel: CancellationToken::new(),
42        }
43    }
44
45    /// Get the current valid token.
46    pub async fn token(&self) -> String {
47        self.current_token.read().await.clone()
48    }
49
50    /// Get the scope this manager is configured for.
51    pub fn scope(&self) -> &str {
52        &self.scope
53    }
54
55    /// Get the audience.
56    pub fn audience(&self) -> &str {
57        &self.audience
58    }
59
60    /// Start the background refresh loop.
61    ///
62    /// The refresh callback is called at `max(ttl * 3/4, ttl - 60s)` intervals
63    /// to ensure overlap before expiry.
64    ///
65    /// # Arguments
66    ///
67    /// * `refresh_fn` - Async function that issues a new token given (scope, audience, ttl_secs)
68    pub fn start_refresh_loop<F, Fut>(&mut self, refresh_fn: F)
69    where
70        F: Fn(String, String, u64) -> Fut + Send + Sync + 'static,
71        Fut: std::future::Future<Output = Result<String, String>> + Send + 'static,
72    {
73        let token = Arc::clone(&self.current_token);
74        let scope = self.scope.clone();
75        let audience = self.audience.clone();
76        let ttl_secs = self.ttl_secs;
77        let cancel = self.cancel.clone();
78
79        // Refresh at max(ttl * 3/4, ttl - 60), with a minimum of 1s to prevent busy-loop.
80        let refresh_interval = Duration::from_secs(std::cmp::max(
81            1,
82            std::cmp::max(ttl_secs * 3 / 4, ttl_secs.saturating_sub(60)),
83        ));
84
85        let handle = tokio::spawn(async move {
86            loop {
87                tokio::select! {
88                    _ = cancel.cancelled() => break,
89                    _ = tokio::time::sleep(refresh_interval) => {
90                        match refresh_fn(scope.clone(), audience.clone(), ttl_secs).await {
91                            Ok(new_token) => {
92                                *token.write().await = new_token;
93                                tracing::debug!(scope = %scope, "Refreshed event token");
94                            }
95                            Err(e) => {
96                                tracing::warn!(
97                                    scope = %scope,
98                                    error = %e,
99                                    "Failed to refresh event token, will retry"
100                                );
101                            }
102                        }
103                    }
104                }
105            }
106        });
107
108        self.refresh_handle = Some(handle);
109    }
110
111    /// Stop the refresh loop.
112    pub fn stop(&self) {
113        self.cancel.cancel();
114    }
115
116    /// Update the token manually (e.g., after initial issuance).
117    pub async fn set_token(&self, token: String) {
118        *self.current_token.write().await = token;
119    }
120}
121
122impl Drop for EventTokenManager {
123    fn drop(&mut self) {
124        self.cancel.cancel();
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use std::sync::atomic::{AtomicU32, Ordering};
132
133    #[tokio::test]
134    async fn test_initial_token() {
135        let mgr = EventTokenManager::new(
136            "initial-jwt".to_owned(),
137            "publish:events:worker.*".to_owned(),
138            "events".to_owned(),
139            600,
140        );
141        assert_eq!(mgr.token().await, "initial-jwt");
142    }
143
144    #[tokio::test]
145    async fn test_set_token() {
146        let mgr =
147            EventTokenManager::new("old".to_owned(), "scope".to_owned(), "aud".to_owned(), 600);
148        mgr.set_token("new".to_owned()).await;
149        assert_eq!(mgr.token().await, "new");
150    }
151
152    #[tokio::test]
153    async fn test_refresh_loop_calls_callback() {
154        let counter = Arc::new(AtomicU32::new(0));
155        let counter_clone = counter.clone();
156
157        let mut mgr = EventTokenManager::new(
158            "initial".to_owned(),
159            "scope".to_owned(),
160            "aud".to_owned(),
161            2, // 2 second TTL → refresh at max(1.5, 0) = 1.5s, but we use min 1s
162        );
163
164        mgr.start_refresh_loop(move |_scope, _aud, _ttl| {
165            let c = counter_clone.clone();
166            async move {
167                c.fetch_add(1, Ordering::SeqCst);
168                Ok(format!("token-{}", c.load(Ordering::SeqCst)))
169            }
170        });
171
172        // Wait enough for at least one refresh
173        tokio::time::sleep(Duration::from_secs(3)).await;
174        mgr.stop();
175
176        assert!(counter.load(Ordering::SeqCst) >= 1);
177        assert!(mgr.token().await.starts_with("token-"));
178    }
179
180    #[tokio::test]
181    async fn test_stop_cancels_refresh() {
182        let mut mgr = EventTokenManager::new(
183            "initial".to_owned(),
184            "scope".to_owned(),
185            "aud".to_owned(),
186            600,
187        );
188
189        mgr.start_refresh_loop(|_s, _a, _t| async { Ok("refreshed".to_owned()) });
190        mgr.stop();
191
192        // Token should still be initial since refresh didn't fire yet
193        assert_eq!(mgr.token().await, "initial");
194    }
195}