Skip to main content

modelexpress_server/
auth.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! ServiceAccount `TokenReview` authentication plus an exact-match allowlist.
5
6mod layer;
7mod token;
8
9pub use layer::AuthLayer;
10pub use token::CallerIdentity;
11
12use std::collections::HashSet;
13use std::fmt;
14use std::hash::{Hash, Hasher};
15use std::time::Duration;
16
17use http::HeaderMap;
18use kube::client::Client;
19use moka::future::Cache;
20use secrecy::ExposeSecret;
21use secrecy::zeroize::Zeroizing;
22use tracing::warn;
23
24use crate::config::{SecurityConfig, ServiceAccountRef};
25use token::{extract_bearer, review_token};
26
27#[derive(Debug, thiserror::Error)]
28pub enum Denial {
29    #[error("missing or invalid service account token")]
30    Unauthenticated,
31    #[error("{0}")]
32    PermissionDenied(String),
33    #[error("authentication backend unavailable")]
34    Unavailable,
35}
36
37impl Denial {
38    pub(crate) fn into_status(self) -> tonic::Status {
39        match self {
40            Self::Unauthenticated => {
41                tonic::Status::unauthenticated("missing or invalid service account token")
42            }
43            Self::PermissionDenied(message) => tonic::Status::permission_denied(message),
44            Self::Unavailable => tonic::Status::unavailable("authentication backend unavailable"),
45        }
46    }
47}
48
49#[derive(Clone)]
50struct TokenCacheKey(Zeroizing<String>);
51
52impl TokenCacheKey {
53    fn new(token: &str) -> Self {
54        Self(Zeroizing::new(token.to_string()))
55    }
56
57    fn as_str(&self) -> &str {
58        self.0.as_str()
59    }
60}
61
62impl fmt::Debug for TokenCacheKey {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str("TokenCacheKey([REDACTED])")
65    }
66}
67
68impl PartialEq for TokenCacheKey {
69    fn eq(&self, other: &Self) -> bool {
70        self.as_str() == other.as_str()
71    }
72}
73
74impl Eq for TokenCacheKey {}
75
76impl Hash for TokenCacheKey {
77    fn hash<H: Hasher>(&self, state: &mut H) {
78        self.as_str().hash(state);
79    }
80}
81
82pub struct AuthState {
83    client: Client,
84    audiences: Vec<String>,
85    allowlist: HashSet<ServiceAccountRef>,
86    token_cache: Cache<TokenCacheKey, CallerIdentity>,
87    negative_cache: Cache<TokenCacheKey, ()>,
88}
89
90impl AuthState {
91    const TOKEN_CACHE_MAX_ENTRIES: u64 = 10_000;
92
93    #[must_use]
94    pub fn new(client: Client, config: &SecurityConfig) -> Self {
95        let ttl = Duration::from_secs(config.cache_ttl_secs);
96        Self {
97            client,
98            audiences: config.token_audiences.clone(),
99            allowlist: config.allowed_service_accounts.iter().cloned().collect(),
100            token_cache: Cache::builder()
101                .time_to_live(ttl)
102                .max_capacity(Self::TOKEN_CACHE_MAX_ENTRIES)
103                .build(),
104            negative_cache: Cache::builder()
105                .time_to_live(ttl)
106                .max_capacity(Self::TOKEN_CACHE_MAX_ENTRIES)
107                .build(),
108        }
109    }
110
111    pub(crate) async fn verify(&self, headers: &HeaderMap) -> Result<CallerIdentity, Denial> {
112        let token = extract_bearer(headers).ok_or(Denial::Unauthenticated)?;
113        let key = TokenCacheKey::new(token.expose_secret());
114
115        if self.negative_cache.get(&key).await.is_some() {
116            return Err(Denial::Unauthenticated);
117        }
118
119        let client = self.client.clone();
120        let audiences = self.audiences.clone();
121        let key_for_review = key.clone();
122        let identity = match self
123            .token_cache
124            .try_get_with(key.clone(), async move {
125                review_token(&client, key_for_review.as_str(), &audiences).await
126            })
127            .await
128        {
129            Ok(identity) => identity,
130            Err(error) => {
131                if error.is_token_rejection() {
132                    self.negative_cache.insert(key, ()).await;
133                    return Err(Denial::Unauthenticated);
134                }
135                warn!(error = %error, "TokenReview backend error");
136                return Err(Denial::Unavailable);
137            }
138        };
139
140        let caller = ServiceAccountRef {
141            namespace: identity.namespace.clone(),
142            service_account: identity.service_account.clone(),
143        };
144        if !self.allowlist.contains(&caller) {
145            return Err(Denial::PermissionDenied(format!(
146                "service account {}:{} is not in the allowlist",
147                identity.namespace, identity.service_account
148            )));
149        }
150
151        Ok(identity)
152    }
153}
154
155#[cfg(test)]
156#[allow(clippy::expect_used)]
157pub(crate) mod test_util {
158    use std::collections::VecDeque;
159    use std::sync::{
160        Arc, Mutex,
161        atomic::{AtomicUsize, Ordering},
162    };
163
164    use http::HeaderMap;
165    use http::header::{AUTHORIZATION, CONTENT_TYPE};
166    use k8s_openapi::api::authentication::v1::{TokenReview, TokenReviewStatus, UserInfo};
167    use kube::client::{Body, Client};
168    use tower::BoxError;
169
170    use crate::config::{AuthMode, SecurityConfig, ServiceAccountRef};
171
172    pub(crate) fn allowed_ref(namespace: &str, service_account: &str) -> ServiceAccountRef {
173        ServiceAccountRef {
174            namespace: namespace.to_string(),
175            service_account: service_account.to_string(),
176        }
177    }
178
179    pub(crate) fn security_config(allowed: Vec<ServiceAccountRef>) -> SecurityConfig {
180        SecurityConfig {
181            mode: Some(AuthMode::Enforce),
182            token_audiences: vec!["modelexpress".to_string()],
183            allowed_service_accounts: allowed,
184            cache_ttl_secs: 60,
185        }
186    }
187
188    pub(crate) fn bearer_headers(token: &str) -> HeaderMap {
189        let mut headers = HeaderMap::new();
190        headers.insert(
191            AUTHORIZATION,
192            format!("Bearer {token}")
193                .parse()
194                .expect("valid bearer header"),
195        );
196        headers
197    }
198
199    pub(crate) fn token_review_for(username: &str) -> TokenReview {
200        TokenReview {
201            status: Some(TokenReviewStatus {
202                authenticated: Some(true),
203                audiences: Some(vec!["modelexpress".to_string()]),
204                user: Some(UserInfo {
205                    username: Some(username.to_string()),
206                    ..Default::default()
207                }),
208                ..Default::default()
209            }),
210            ..Default::default()
211        }
212    }
213
214    pub(crate) fn unauthenticated_review(error: &str) -> TokenReview {
215        TokenReview {
216            status: Some(TokenReviewStatus {
217                authenticated: Some(false),
218                error: Some(error.to_string()),
219                ..Default::default()
220            }),
221            ..Default::default()
222        }
223    }
224
225    pub(crate) fn review_without_user() -> TokenReview {
226        TokenReview {
227            status: Some(TokenReviewStatus {
228                authenticated: Some(true),
229                ..Default::default()
230            }),
231            ..Default::default()
232        }
233    }
234
235    pub(crate) enum FakeResponse {
236        Review(Box<TokenReview>),
237        Error(http::StatusCode),
238    }
239
240    pub(crate) fn fake_kube_client(reviews: Vec<TokenReview>) -> (Client, Arc<AtomicUsize>) {
241        fake_kube_client_with_responses(
242            reviews
243                .into_iter()
244                .map(|r| FakeResponse::Review(Box::new(r)))
245                .collect(),
246        )
247    }
248
249    pub(crate) fn fake_kube_client_with_responses(
250        responses: Vec<FakeResponse>,
251    ) -> (Client, Arc<AtomicUsize>) {
252        let responses = Arc::new(Mutex::new(VecDeque::from(responses)));
253        let calls = Arc::new(AtomicUsize::new(0));
254
255        let service = tower::service_fn({
256            let responses = responses.clone();
257            let calls = calls.clone();
258            move |_request: http::Request<Body>| {
259                let responses = responses.clone();
260                let calls = calls.clone();
261                async move {
262                    calls.fetch_add(1, Ordering::SeqCst);
263                    let response_item = responses
264                        .lock()
265                        .expect("fake response queue lock")
266                        .pop_front()
267                        .expect("fake response");
268                    let response = match response_item {
269                        FakeResponse::Review(review) => {
270                            let body = serde_json::to_vec(&*review).expect("serialize TokenReview");
271                            http::Response::builder()
272                                .status(http::StatusCode::OK)
273                                .header(CONTENT_TYPE, "application/json")
274                                .body(Body::from(body))
275                                .expect("fake TokenReview response body")
276                        }
277                        FakeResponse::Error(status) => http::Response::builder()
278                            .status(status)
279                            .body(Body::empty())
280                            .expect("fake error response body"),
281                    };
282                    Ok::<_, BoxError>(response)
283                }
284            }
285        });
286
287        (Client::new(service, "default"), calls)
288    }
289}
290
291#[cfg(test)]
292#[allow(clippy::expect_used)]
293mod tests {
294    use super::*;
295    use std::sync::atomic::Ordering;
296
297    use test_util::{
298        allowed_ref, bearer_headers, fake_kube_client, security_config, token_review_for,
299        unauthenticated_review,
300    };
301
302    #[test]
303    fn unauthenticated_maps_to_grpc_code() {
304        let status = Denial::Unauthenticated.into_status();
305        assert_eq!(status.code(), tonic::Code::Unauthenticated);
306    }
307
308    #[test]
309    fn permission_denied_maps_to_grpc_code() {
310        let status = Denial::PermissionDenied("nope".to_string()).into_status();
311        assert_eq!(status.code(), tonic::Code::PermissionDenied);
312        assert_eq!(status.message(), "nope");
313    }
314
315    #[test]
316    fn unavailable_maps_to_grpc_code() {
317        let status = Denial::Unavailable.into_status();
318        assert_eq!(status.code(), tonic::Code::Unavailable);
319    }
320
321    #[tokio::test]
322    async fn verify_accepts_allowlisted_identity_and_uses_positive_cache() {
323        let (client, calls) =
324            fake_kube_client(vec![token_review_for("system:serviceaccount:vllm:worker")]);
325        let config = security_config(vec![allowed_ref("vllm", "worker")]);
326        let state = AuthState::new(client, &config);
327        let headers = bearer_headers("good-token");
328
329        let first = state.verify(&headers).await.expect("first token review");
330        let second = state.verify(&headers).await.expect("cached token review");
331
332        assert_eq!(first.namespace, "vllm");
333        assert_eq!(first.service_account, "worker");
334        assert_eq!(second.namespace, "vllm");
335        assert_eq!(calls.load(Ordering::SeqCst), 1);
336    }
337
338    #[tokio::test]
339    async fn verify_rejects_identity_outside_allowlist() {
340        let (client, _calls) =
341            fake_kube_client(vec![token_review_for("system:serviceaccount:other:worker")]);
342        let config = security_config(vec![allowed_ref("vllm", "worker")]);
343        let state = AuthState::new(client, &config);
344        let headers = bearer_headers("other-token");
345
346        let error = state
347            .verify(&headers)
348            .await
349            .expect_err("non-allowlisted service account should be denied");
350
351        assert!(
352            matches!(error, Denial::PermissionDenied(message) if message.contains("other:worker"))
353        );
354    }
355
356    #[tokio::test]
357    async fn verify_negative_caches_definitive_token_rejections() {
358        let (client, calls) = fake_kube_client(vec![unauthenticated_review("expired")]);
359        let config = security_config(vec![allowed_ref("vllm", "worker")]);
360        let state = AuthState::new(client, &config);
361        let headers = bearer_headers("expired-token");
362
363        assert!(matches!(
364            state.verify(&headers).await,
365            Err(Denial::Unauthenticated)
366        ));
367        assert!(matches!(
368            state.verify(&headers).await,
369            Err(Denial::Unauthenticated)
370        ));
371        assert_eq!(calls.load(Ordering::SeqCst), 1);
372    }
373
374    #[tokio::test]
375    async fn verify_returns_unavailable_for_api_errors_without_caching() {
376        use test_util::FakeResponse;
377
378        let (client, calls) = test_util::fake_kube_client_with_responses(vec![
379            FakeResponse::Error(http::StatusCode::INTERNAL_SERVER_ERROR),
380            FakeResponse::Error(http::StatusCode::INTERNAL_SERVER_ERROR),
381        ]);
382        let config = security_config(vec![allowed_ref("vllm", "worker")]);
383        let state = AuthState::new(client, &config);
384        let headers = bearer_headers("token");
385
386        assert!(matches!(
387            state.verify(&headers).await,
388            Err(Denial::Unavailable)
389        ));
390        assert!(matches!(
391            state.verify(&headers).await,
392            Err(Denial::Unavailable)
393        ));
394        assert_eq!(calls.load(Ordering::SeqCst), 2);
395    }
396}