llm-registry-api 0.1.0

API layer for the LLM Registry - REST, GraphQL, and gRPC interfaces for model management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Authentication middleware
//!
//! This module provides JWT-based authentication middleware for protecting API routes.

use axum::{
    body::Body,
    extract::{Request, State},
    http::{header::AUTHORIZATION, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::sync::Arc;
use tracing::{debug, warn};

use crate::{
    error::ErrorResponse,
    jwt::{Claims, JwtManager, TokenError},
};

/// Extension for storing authenticated user claims in requests
#[derive(Debug, Clone)]
pub struct AuthUser {
    /// JWT claims for the authenticated user
    pub claims: Claims,
}

impl AuthUser {
    /// Create new authenticated user
    pub fn new(claims: Claims) -> Self {
        Self { claims }
    }

    /// Get user ID
    pub fn user_id(&self) -> &str {
        &self.claims.sub
    }

    /// Get user email
    pub fn email(&self) -> Option<&str> {
        self.claims.email.as_deref()
    }

    /// Check if user has a role
    pub fn has_role(&self, role: &str) -> bool {
        self.claims.has_role(role)
    }

    /// Check if user has any of the roles
    pub fn has_any_role(&self, roles: &[&str]) -> bool {
        self.claims.has_any_role(roles)
    }

    /// Check if user has all of the roles
    pub fn has_all_roles(&self, roles: &[&str]) -> bool {
        self.claims.has_all_roles(roles)
    }
}

/// Authentication state containing JWT manager
#[derive(Clone)]
pub struct AuthState {
    jwt_manager: Arc<JwtManager>,
}

impl AuthState {
    /// Create new auth state
    pub fn new(jwt_manager: JwtManager) -> Self {
        Self {
            jwt_manager: Arc::new(jwt_manager),
        }
    }

    /// Get JWT manager reference
    pub fn jwt_manager(&self) -> &JwtManager {
        &self.jwt_manager
    }
}

/// Required authentication middleware
///
/// This middleware requires a valid JWT token in the Authorization header.
/// If authentication fails, it returns a 401 Unauthorized response.
///
/// # Usage
///
/// ```rust,no_run
/// use axum::{Router, routing::get, middleware};
/// use llm_registry_api::auth::{require_auth, AuthState};
/// use llm_registry_api::jwt::{JwtConfig, JwtManager};
///
/// # async fn example() {
/// let jwt_manager = JwtManager::new(JwtConfig::default()).unwrap();
/// let auth_state = AuthState::new(jwt_manager);
///
/// let app = Router::new()
///     .route("/protected", get(|| async { "Protected content" }))
///     .layer(middleware::from_fn_with_state(auth_state.clone(), require_auth));
/// # }
/// ```
pub async fn require_auth(
    State(auth_state): State<AuthState>,
    mut request: Request,
    next: Next,
) -> Result<Response, AuthError> {
    debug!("Authenticating request");

    // Extract Authorization header
    let auth_header = request
        .headers()
        .get(AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .ok_or(AuthError::MissingToken)?;

    // Extract token from header
    let token = JwtManager::extract_token_from_header(auth_header)
        .map_err(|_| AuthError::InvalidToken)?;

    // Validate token
    let claims = auth_state
        .jwt_manager
        .validate_token(token)
        .map_err(|e| match e {
            TokenError::Expired => AuthError::ExpiredToken,
            TokenError::NotYetValid => AuthError::InvalidToken,
            _ => AuthError::InvalidToken,
        })?;

    debug!("User authenticated: {}", claims.sub);

    // Add user to request extensions
    request.extensions_mut().insert(AuthUser::new(claims));

    Ok(next.run(request).await)
}

/// Optional authentication middleware
///
/// This middleware attempts to authenticate the user but does not fail if
/// authentication is unsuccessful. Use this for endpoints that have optional
/// authentication (e.g., public content that can be personalized for logged-in users).
///
/// # Usage
///
/// ```rust,no_run
/// use axum::{Router, routing::get, middleware};
/// use llm_registry_api::auth::{optional_auth, AuthState};
/// use llm_registry_api::jwt::{JwtConfig, JwtManager};
///
/// # async fn example() {
/// let jwt_manager = JwtManager::new(JwtConfig::default()).unwrap();
/// let auth_state = AuthState::new(jwt_manager);
///
/// let app = Router::new()
///     .route("/public", get(|| async { "Public content" }))
///     .layer(middleware::from_fn_with_state(auth_state.clone(), optional_auth));
/// # }
/// ```
pub async fn optional_auth(
    State(auth_state): State<AuthState>,
    mut request: Request,
    next: Next,
) -> Response {
    debug!("Attempting optional authentication");

    // Try to extract and validate token
    if let Some(auth_header) = request.headers().get(AUTHORIZATION) {
        if let Ok(header_str) = auth_header.to_str() {
            if let Ok(token) = JwtManager::extract_token_from_header(header_str) {
                if let Ok(claims) = auth_state.jwt_manager.validate_token(token) {
                    debug!("User optionally authenticated: {}", claims.sub);
                    request.extensions_mut().insert(AuthUser::new(claims));
                }
            }
        }
    }

    next.run(request).await
}

/// Role-based authentication middleware
///
/// This middleware requires authentication AND checks if the user has one of the
/// specified roles.
///
/// # Usage
///
/// ```rust,no_run
/// use axum::{Router, routing::get, middleware};
/// use llm_registry_api::auth::{require_role, AuthState};
/// use llm_registry_api::jwt::{JwtConfig, JwtManager};
///
/// # async fn example() {
/// let jwt_manager = JwtManager::new(JwtConfig::default()).unwrap();
/// let auth_state = AuthState::new(jwt_manager);
///
/// let roles = vec!["admin".to_string(), "moderator".to_string()];
///
/// let app = Router::new()
///     .route("/admin", get(|| async { "Admin content" }))
///     .layer(middleware::from_fn_with_state(
///         (auth_state.clone(), roles),
///         require_role,
///     ));
/// # }
/// ```
pub async fn require_role(
    State((auth_state, allowed_roles)): State<(AuthState, Vec<String>)>,
    mut request: Request,
    next: Next,
) -> Result<Response, AuthError> {
    debug!("Authenticating request with role check");

    // First authenticate
    let auth_header = request
        .headers()
        .get(AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .ok_or(AuthError::MissingToken)?;

    let token = JwtManager::extract_token_from_header(auth_header)
        .map_err(|_| AuthError::InvalidToken)?;

    let claims = auth_state
        .jwt_manager
        .validate_token(token)
        .map_err(|e| match e {
            TokenError::Expired => AuthError::ExpiredToken,
            TokenError::NotYetValid => AuthError::InvalidToken,
            _ => AuthError::InvalidToken,
        })?;

    // Check roles
    let role_refs: Vec<&str> = allowed_roles.iter().map(|s| s.as_str()).collect();
    if !claims.has_any_role(&role_refs) {
        warn!("User {} lacks required role", claims.sub);
        return Err(AuthError::InsufficientPermissions);
    }

    debug!("User authenticated with role: {}", claims.sub);
    request.extensions_mut().insert(AuthUser::new(claims));

    Ok(next.run(request).await)
}

/// Extract authenticated user from request
///
/// This is a helper function to extract the AuthUser from request extensions.
/// Use this in your handlers after authentication middleware.
///
/// # Example
///
/// ```rust,no_run
/// use axum::{extract::Extension};
/// use llm_registry_api::auth::AuthUser;
///
/// async fn my_handler(Extension(user): Extension<AuthUser>) -> String {
///     format!("Hello, user {}", user.user_id())
/// }
/// ```
pub fn extract_user(request: &Request<Body>) -> Result<&AuthUser, AuthError> {
    request
        .extensions()
        .get::<AuthUser>()
        .ok_or(AuthError::Unauthenticated)
}

/// Authentication errors
#[derive(Debug)]
pub enum AuthError {
    /// Missing authentication token
    MissingToken,

    /// Invalid token format or signature
    InvalidToken,

    /// Token has expired
    ExpiredToken,

    /// User is not authenticated
    Unauthenticated,

    /// User lacks required permissions
    InsufficientPermissions,
}

impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AuthError::MissingToken => (
                StatusCode::UNAUTHORIZED,
                "Missing authentication token",
            ),
            AuthError::InvalidToken => (
                StatusCode::UNAUTHORIZED,
                "Invalid authentication token",
            ),
            AuthError::ExpiredToken => (
                StatusCode::UNAUTHORIZED,
                "Authentication token has expired",
            ),
            AuthError::Unauthenticated => (
                StatusCode::UNAUTHORIZED,
                "Authentication required",
            ),
            AuthError::InsufficientPermissions => (
                StatusCode::FORBIDDEN,
                "Insufficient permissions",
            ),
        };

        let error_response = ErrorResponse {
            status: status.as_u16(),
            error: message.to_string(),
            code: None,
            timestamp: chrono::Utc::now(),
        };

        (status, axum::Json(error_response)).into_response()
    }
}

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthError::MissingToken => write!(f, "Missing authentication token"),
            AuthError::InvalidToken => write!(f, "Invalid authentication token"),
            AuthError::ExpiredToken => write!(f, "Authentication token has expired"),
            AuthError::Unauthenticated => write!(f, "Authentication required"),
            AuthError::InsufficientPermissions => write!(f, "Insufficient permissions"),
        }
    }
}

impl std::error::Error for AuthError {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jwt::{JwtConfig, JwtManager};
    use axum::{
        body::Body,
        extract::Extension,
        http::{Request, StatusCode},
        middleware,
        routing::get,
        Router,
    };
    use tower::ServiceExt;

    fn create_test_jwt_manager() -> JwtManager {
        let config = JwtConfig::new("test-secret-key")
            .with_issuer("test")
            .with_audience("test");
        JwtManager::new(config).unwrap()
    }

    async fn protected_handler(Extension(user): axum::extract::Extension<AuthUser>) -> String {
        format!("Hello, {}", user.user_id())
    }

    #[tokio::test]
    async fn test_require_auth_with_valid_token() {
        let jwt_manager = create_test_jwt_manager();
        let token = jwt_manager.generate_token("user123").unwrap();
        let auth_state = AuthState::new(jwt_manager);

        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn_with_state(
                auth_state.clone(),
                require_auth,
            ));

        let request = Request::builder()
            .uri("/protected")
            .header(AUTHORIZATION, format!("Bearer {}", token))
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_require_auth_without_token() {
        let jwt_manager = create_test_jwt_manager();
        let auth_state = AuthState::new(jwt_manager);

        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn_with_state(
                auth_state.clone(),
                require_auth,
            ));

        let request = Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_require_auth_with_invalid_token() {
        let jwt_manager = create_test_jwt_manager();
        let auth_state = AuthState::new(jwt_manager);

        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn_with_state(
                auth_state.clone(),
                require_auth,
            ));

        let request = Request::builder()
            .uri("/protected")
            .header(AUTHORIZATION, "Bearer invalid.token.here")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_optional_auth_with_token() {
        let jwt_manager = create_test_jwt_manager();
        let token = jwt_manager.generate_token("user123").unwrap();
        let auth_state = AuthState::new(jwt_manager);

        async fn handler(user: Option<axum::extract::Extension<AuthUser>>) -> String {
            match user {
                Some(Extension(u)) => format!("Hello, {}", u.user_id()),
                None => "Hello, guest".to_string(),
            }
        }

        let app = Router::new()
            .route("/public", get(handler))
            .layer(middleware::from_fn_with_state(
                auth_state.clone(),
                optional_auth,
            ));

        let request = Request::builder()
            .uri("/public")
            .header(AUTHORIZATION, format!("Bearer {}", token))
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_optional_auth_without_token() {
        let jwt_manager = create_test_jwt_manager();
        let auth_state = AuthState::new(jwt_manager);

        async fn handler() -> &'static str {
            "Public content"
        }

        let app = Router::new()
            .route("/public", get(handler))
            .layer(middleware::from_fn_with_state(
                auth_state.clone(),
                optional_auth,
            ));

        let request = Request::builder()
            .uri("/public")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_auth_user() {
        let claims = crate::jwt::Claims::new("user123", "test", "test", 3600)
            .with_email("user@example.com")
            .with_role("admin");

        let auth_user = AuthUser::new(claims);

        assert_eq!(auth_user.user_id(), "user123");
        assert_eq!(auth_user.email(), Some("user@example.com"));
        assert!(auth_user.has_role("admin"));
        assert!(!auth_user.has_role("moderator"));
    }
}