perfgate-server 0.15.1

REST API server for centralized baseline 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Authentication and authorization middleware.
//!
//! This module provides API key and JWT token validation for the baseline service.

use axum::{
    Json,
    extract::{Request, State},
    http::{HeaderMap, StatusCode, header},
    middleware::Next,
    response::IntoResponse,
};
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, errors::ErrorKind};
pub use perfgate_auth::{ApiKey, JwtClaims, Role, Scope, validate_key_format};
use perfgate_error::AuthError;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::warn;

use crate::models::ApiError;
use crate::oidc::OidcRegistry;
use crate::storage::KeyStore;

/// JWT validation settings.
#[derive(Clone)]
pub struct JwtConfig {
    secret: Vec<u8>,
    issuer: Option<String>,
    audience: Option<String>,
}

impl JwtConfig {
    /// Creates an HS256 JWT configuration from raw secret bytes.
    pub fn hs256(secret: impl Into<Vec<u8>>) -> Self {
        Self {
            secret: secret.into(),
            issuer: None,
            audience: None,
        }
    }

    /// Sets the expected issuer claim.
    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Sets the expected audience claim.
    pub fn audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }

    /// Returns the configured secret bytes.
    pub fn secret_bytes(&self) -> &[u8] {
        &self.secret
    }

    fn validation(&self) -> Validation {
        let mut validation = Validation::new(Algorithm::HS256);
        if let Some(issuer) = &self.issuer {
            validation.set_issuer(&[issuer.as_str()]);
        }
        if let Some(audience) = &self.audience {
            validation.set_audience(&[audience.as_str()]);
        }
        validation
    }
}

impl std::fmt::Debug for JwtConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JwtConfig")
            .field("secret", &"<redacted>")
            .field("issuer", &self.issuer)
            .field("audience", &self.audience)
            .finish()
    }
}

/// Authentication state shared by middleware.
#[derive(Clone)]
pub struct AuthState {
    /// In-memory API key store (for CLI-provided keys).
    pub key_store: Arc<ApiKeyStore>,

    /// Persistent key store (database-backed).
    pub persistent_key_store: Option<Arc<dyn KeyStore>>,

    /// Optional JWT validation settings.
    pub jwt: Option<JwtConfig>,

    /// OIDC provider registry (may contain zero or more providers).
    pub oidc: OidcRegistry,
}

impl AuthState {
    /// Creates auth state from a key store and optional JWT/OIDC configuration.
    pub fn new(key_store: Arc<ApiKeyStore>, jwt: Option<JwtConfig>, oidc: OidcRegistry) -> Self {
        Self {
            key_store,
            persistent_key_store: None,
            jwt,
            oidc,
        }
    }

    /// Adds a persistent key store for database-backed key validation.
    pub fn with_persistent_key_store(mut self, store: Arc<dyn KeyStore>) -> Self {
        self.persistent_key_store = Some(store);
        self
    }
}

/// Authenticated user context extracted from requests.
#[derive(Debug, Clone)]
pub struct AuthContext {
    /// API key information
    pub api_key: ApiKey,

    /// Source IP address
    pub source_ip: Option<String>,
}

/// In-memory API key store for development and testing.
#[derive(Debug, Default)]
pub struct ApiKeyStore {
    /// Keys indexed by key hash
    keys: Arc<RwLock<HashMap<String, ApiKey>>>,
}

impl ApiKeyStore {
    /// Creates a new empty key store.
    pub fn new() -> Self {
        Self {
            keys: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Adds an API key to the store.
    pub async fn add_key(&self, key: ApiKey, raw_key: &str) {
        let hash = hash_api_key(raw_key);
        let mut keys = self.keys.write().await;
        keys.insert(hash, key);
    }

    /// Looks up an API key by its hash.
    pub async fn get_key(&self, raw_key: &str) -> Option<ApiKey> {
        let hash = hash_api_key(raw_key);
        let keys = self.keys.read().await;
        keys.get(&hash).cloned()
    }

    /// Removes an API key from the store.
    pub async fn remove_key(&self, raw_key: &str) -> bool {
        let hash = hash_api_key(raw_key);
        let mut keys = self.keys.write().await;
        keys.remove(&hash).is_some()
    }

    /// Lists all API keys (without sensitive data).
    pub async fn list_keys(&self) -> Vec<ApiKey> {
        let keys = self.keys.read().await;
        keys.values().cloned().collect()
    }
}

enum Credentials {
    ApiKey(String),
    Jwt(String),
}

/// Hashes an API key for storage.
fn hash_api_key(key: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(key.as_bytes());
    format!("{:x}", hasher.finalize())
}

fn extract_credentials(headers: &HeaderMap) -> Option<Credentials> {
    let auth_header = headers.get(header::AUTHORIZATION)?.to_str().ok()?;

    if let Some(key) = auth_header.strip_prefix("Bearer ") {
        return Some(Credentials::ApiKey(key.to_string()));
    }

    if let Some(token) = auth_header.strip_prefix("Token ") {
        return Some(Credentials::Jwt(token.to_string()));
    }

    None
}

fn source_ip(headers: &HeaderMap) -> Option<String> {
    headers
        .get("X-Forwarded-For")
        .and_then(|v| v.to_str().ok())
        .map(ToOwned::to_owned)
}

fn unauthorized(message: &str) -> (StatusCode, Json<ApiError>) {
    (
        StatusCode::UNAUTHORIZED,
        Json(ApiError::unauthorized(message)),
    )
}

async fn authenticate_api_key(
    auth_state: &AuthState,
    api_key_str: &str,
    headers: &HeaderMap,
) -> Result<AuthContext, (StatusCode, Json<ApiError>)> {
    validate_key_format(api_key_str).map_err(|_| {
        warn!(
            key_prefix = &api_key_str[..10.min(api_key_str.len())],
            "Invalid API key format"
        );
        unauthorized("Invalid API key format")
    })?;

    // Try the in-memory store first (CLI-provided keys)
    if let Some(api_key) = auth_state.key_store.get_key(api_key_str).await {
        if api_key.is_expired() {
            warn!(key_id = %api_key.id, "API key expired");
            return Err(unauthorized("API key has expired"));
        }
        return Ok(AuthContext {
            api_key,
            source_ip: source_ip(headers),
        });
    }

    // Try the persistent key store (database-backed keys)
    if let Some(persistent) = &auth_state.persistent_key_store
        && let Ok(Some(record)) = persistent.validate_key(api_key_str).await
    {
        let mut api_key = ApiKey::new(
            record.id.clone(),
            record.description.clone(),
            record.project.clone(),
            record.role,
        );
        // Apply benchmark pattern as regex
        api_key.benchmark_regex = record.pattern.clone();
        api_key.expires_at = record.expires_at;
        api_key.created_at = record.created_at;

        return Ok(AuthContext {
            api_key,
            source_ip: source_ip(headers),
        });
    }

    warn!(
        key_prefix = &api_key_str[..10.min(api_key_str.len())],
        "Invalid API key"
    );
    Err(unauthorized("Invalid API key"))
}

fn validate_jwt(token: &str, config: &JwtConfig) -> Result<JwtClaims, AuthError> {
    let validation = config.validation();

    decode::<JwtClaims>(
        token,
        &DecodingKey::from_secret(config.secret_bytes()),
        &validation,
    )
    .map(|data| data.claims)
    .map_err(|error| match error.kind() {
        ErrorKind::ExpiredSignature => AuthError::ExpiredToken,
        _ => AuthError::InvalidToken(error.to_string()),
    })
}

async fn authenticate_jwt(
    auth_state: &AuthState,
    token: &str,
    headers: &HeaderMap,
) -> Result<AuthContext, (StatusCode, Json<ApiError>)> {
    // Try static JWT config if available
    if let Some(config) = &auth_state.jwt {
        match validate_jwt(token, config) {
            Ok(claims) => {
                return Ok(AuthContext {
                    api_key: api_key_from_jwt_claims(&claims),
                    source_ip: source_ip(headers),
                });
            }
            Err(e) => {
                // If we don't have OIDC providers, fail here.
                // Otherwise, fall through to OIDC.
                if !auth_state.oidc.has_providers() {
                    match &e {
                        AuthError::ExpiredToken => warn!("Expired JWT token"),
                        AuthError::InvalidToken(_) => warn!("Invalid JWT token"),
                        _ => {}
                    }
                    return Err(unauthorized(&e.to_string()));
                }
            }
        }
    }

    // Try OIDC providers if any are configured
    if auth_state.oidc.has_providers() {
        match auth_state.oidc.validate_token(token).await {
            Ok(api_key) => {
                return Ok(AuthContext {
                    api_key,
                    source_ip: source_ip(headers),
                });
            }
            Err(e) => {
                match &e {
                    AuthError::ExpiredToken => warn!("Expired OIDC token"),
                    AuthError::InvalidToken(msg) => warn!("Invalid OIDC token: {}", msg),
                    _ => {}
                }
                return Err(unauthorized(&e.to_string()));
            }
        }
    }

    warn!("JWT token received but no JWT or OIDC authentication is configured");
    Err(unauthorized("JWT/OIDC authentication is not configured"))
}

fn api_key_from_jwt_claims(claims: &JwtClaims) -> ApiKey {
    ApiKey {
        id: format!("jwt:{}", claims.sub),
        name: format!("JWT {}", claims.sub),
        project_id: claims.project_id.clone(),
        scopes: claims.scopes.clone(),
        role: Role::from_scopes(&claims.scopes),
        benchmark_regex: None,
        expires_at: Some(
            chrono::DateTime::<chrono::Utc>::from_timestamp(claims.exp as i64, 0)
                .unwrap_or_else(chrono::Utc::now),
        ),
        created_at: claims
            .iat
            .and_then(|iat| chrono::DateTime::<chrono::Utc>::from_timestamp(iat as i64, 0))
            .unwrap_or_else(chrono::Utc::now),
        last_used_at: None,
    }
}

/// Authentication middleware.
pub async fn auth_middleware(
    State(auth_state): State<AuthState>,
    mut request: Request,
    next: Next,
) -> Result<impl IntoResponse, (StatusCode, Json<ApiError>)> {
    // Skip auth for health endpoint
    if request.uri().path() == "/health" {
        return Ok(next.run(request).await);
    }

    let auth_ctx = match extract_credentials(request.headers()) {
        Some(Credentials::ApiKey(api_key)) => {
            authenticate_api_key(&auth_state, &api_key, request.headers()).await?
        }
        Some(Credentials::Jwt(token)) => {
            authenticate_jwt(&auth_state, &token, request.headers()).await?
        }
        None => {
            warn!("Missing authentication header");
            return Err(unauthorized("Missing authentication header"));
        }
    };

    request.extensions_mut().insert(auth_ctx);

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

/// Local-mode middleware that injects a synthetic admin auth context.
///
/// `perfgate serve` runs the server in single-user local mode with
/// authentication disabled. Many handlers still depend on `AuthContext` for
/// scope checks and audit metadata, so local mode synthesizes an admin context
/// instead of skipping the extension entirely.
pub async fn local_mode_auth_middleware(mut request: Request, next: Next) -> impl IntoResponse {
    let auth_ctx = AuthContext {
        api_key: ApiKey::new(
            "local-mode".to_string(),
            "Local Mode".to_string(),
            "local".to_string(),
            Role::Admin,
        ),
        source_ip: source_ip(request.headers()),
    };
    request.extensions_mut().insert(auth_ctx);
    next.run(request).await
}

/// Checks if the current auth context has the required scope, project access, and benchmark access.
/// Returns an error response if the scope is not present, project mismatch, or benchmark restricted.
pub fn check_scope(
    auth_ctx: Option<&AuthContext>,
    project_id: &str,
    benchmark: Option<&str>,
    scope: Scope,
) -> Result<(), (StatusCode, Json<ApiError>)> {
    let ctx = match auth_ctx {
        Some(ctx) => ctx,
        None => {
            return Err((
                StatusCode::UNAUTHORIZED,
                Json(ApiError::unauthorized("Authentication required")),
            ));
        }
    };

    // 1. Check Scope
    if !ctx.api_key.has_scope(scope) {
        warn!(
            key_id = %ctx.api_key.id,
            required_scope = %scope,
            actual_role = %ctx.api_key.role,
            "Insufficient permissions: scope mismatch"
        );
        return Err((
            StatusCode::FORBIDDEN,
            Json(ApiError::forbidden(&format!(
                "Requires '{}' permission",
                scope
            ))),
        ));
    }

    // 2. Check Project Isolation
    // Global admins (those with Scope::Admin) can access any project.
    // Otherwise, the key's project_id must match the requested project_id.
    if !ctx.api_key.has_scope(Scope::Admin) && ctx.api_key.project_id != project_id {
        warn!(
            key_id = %ctx.api_key.id,
            key_project = %ctx.api_key.project_id,
            requested_project = %project_id,
            "Insufficient permissions: project isolation violation"
        );
        return Err((
            StatusCode::FORBIDDEN,
            Json(ApiError::forbidden(&format!(
                "Key is restricted to project '{}'",
                ctx.api_key.project_id
            ))),
        ));
    }

    // 3. Check Benchmark Restriction
    // If the key has a benchmark_regex, all accessed benchmarks must match it.
    if let (Some(regex_str), Some(bench)) = (&ctx.api_key.benchmark_regex, benchmark) {
        let regex = regex::Regex::new(regex_str).map_err(|e| {
            warn!(key_id = %ctx.api_key.id, regex = %regex_str, error = %e, "Invalid benchmark regex in API key");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::internal_error("Invalid security configuration")),
            )
        })?;

        if !regex.is_match(bench) {
            warn!(
                key_id = %ctx.api_key.id,
                benchmark = %bench,
                regex = %regex_str,
                "Insufficient permissions: benchmark restriction violation"
            );
            return Err((
                StatusCode::FORBIDDEN,
                Json(ApiError::forbidden(&format!(
                    "Key is restricted to benchmarks matching '{}'",
                    regex_str
                ))),
            ));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{Extension, Router, routing::get};
    use jsonwebtoken::{Header, encode};
    use perfgate_auth::generate_api_key;
    use tower::ServiceExt;
    use uselesskey::{Factory, HmacFactoryExt, HmacSpec, Seed};
    use uselesskey_jsonwebtoken::JwtKeyExt;

    fn test_jwt_config() -> JwtConfig {
        let seed = Seed::from_env_value("perfgate-server-auth-tests").unwrap();
        let factory = Factory::deterministic(seed);
        let fixture = factory.hmac("jwt-auth", HmacSpec::hs256());
        JwtConfig::hs256(fixture.secret_bytes())
            .issuer("perfgate-tests")
            .audience("perfgate")
    }

    fn create_test_claims(scopes: Vec<Scope>, exp: u64) -> JwtClaims {
        JwtClaims {
            sub: "ci-bot".to_string(),
            project_id: "project-1".to_string(),
            scopes,
            exp,
            iat: Some(chrono::Utc::now().timestamp() as u64),
            iss: Some("perfgate-tests".to_string()),
            aud: Some("perfgate".to_string()),
        }
    }

    fn create_test_token(claims: &JwtClaims) -> String {
        let seed = Seed::from_env_value("perfgate-server-auth-tests").unwrap();
        let factory = Factory::deterministic(seed);
        let fixture = factory.hmac("jwt-auth", HmacSpec::hs256());
        encode(&Header::default(), claims, &fixture.encoding_key()).unwrap()
    }

    fn auth_test_router(auth_state: AuthState) -> Router {
        Router::new()
            .route(
                "/protected",
                get(|Extension(auth_ctx): Extension<AuthContext>| async move {
                    auth_ctx.api_key.id
                }),
            )
            .layer(axum::middleware::from_fn_with_state(
                auth_state,
                auth_middleware,
            ))
    }

    fn local_auth_test_router() -> Router {
        Router::new()
            .route(
                "/protected",
                get(|Extension(auth_ctx): Extension<AuthContext>| async move {
                    auth_ctx.api_key.role.to_string()
                }),
            )
            .layer(axum::middleware::from_fn(local_mode_auth_middleware))
    }

    #[tokio::test]
    async fn test_api_key_store() {
        let store = ApiKeyStore::new();
        let raw_key = generate_api_key(false);
        let key = ApiKey::new(
            "key-1".to_string(),
            "Test Key".to_string(),
            "project-1".to_string(),
            Role::Contributor,
        );

        store.add_key(key.clone(), &raw_key).await;

        let retrieved = store.get_key(&raw_key).await;
        assert!(retrieved.is_some());
        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved.id, "key-1");
        assert_eq!(retrieved.role, Role::Contributor);

        let keys = store.list_keys().await;
        assert_eq!(keys.len(), 1);

        let removed = store.remove_key(&raw_key).await;
        assert!(removed);

        let retrieved = store.get_key(&raw_key).await;
        assert!(retrieved.is_none());
    }

    #[tokio::test]
    async fn test_auth_middleware_accepts_api_key() {
        let store = Arc::new(ApiKeyStore::new());
        let key = "pg_test_abcdefghijklmnopqrstuvwxyz123456";
        store
            .add_key(
                ApiKey::new(
                    "api-key-1".to_string(),
                    "API Key".to_string(),
                    "project-1".to_string(),
                    Role::Viewer,
                ),
                key,
            )
            .await;

        let response = auth_test_router(AuthState::new(store, None, Default::default()))
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .header(header::AUTHORIZATION, format!("Bearer {}", key))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_auth_middleware_accepts_jwt_token() {
        let claims = create_test_claims(
            vec![Scope::Read, Scope::Promote],
            (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp() as u64,
        );
        let token = create_test_token(&claims);

        let response = auth_test_router(AuthState::new(
            Arc::new(ApiKeyStore::new()),
            Some(test_jwt_config()),
            Default::default(),
        ))
        .oneshot(
            Request::builder()
                .uri("/protected")
                .header(header::AUTHORIZATION, format!("Token {}", token))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_auth_middleware_rejects_jwt_when_unconfigured() {
        let claims = create_test_claims(
            vec![Scope::Read],
            (chrono::Utc::now() + chrono::Duration::minutes(5)).timestamp() as u64,
        );
        let token = create_test_token(&claims);

        let response = auth_test_router(AuthState::new(
            Arc::new(ApiKeyStore::new()),
            None,
            Default::default(),
        ))
        .oneshot(
            Request::builder()
                .uri("/protected")
                .header(header::AUTHORIZATION, format!("Token {}", token))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_local_mode_auth_middleware_injects_admin_context() {
        let response = local_auth_test_router()
            .oneshot(
                Request::builder()
                    .uri("/protected")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_hash_api_key() {
        let key = "pg_live_test123456789012345678901234567890";
        let hash1 = hash_api_key(key);
        let hash2 = hash_api_key(key);

        assert_eq!(hash1, hash2);

        let different_hash = hash_api_key("pg_live_different1234567890123456789012");
        assert_ne!(hash1, different_hash);
    }

    #[test]
    fn test_check_scope_project_isolation() {
        let key = ApiKey::new(
            "k1".to_string(),
            "n1".to_string(),
            "project-a".to_string(),
            Role::Contributor,
        );
        let ctx = AuthContext {
            api_key: key,
            source_ip: None,
        };

        // Same project, correct scope -> OK
        assert!(check_scope(Some(&ctx), "project-a", None, Scope::Write).is_ok());
        assert!(check_scope(Some(&ctx), "project-a", None, Scope::Read).is_ok());

        // Same project, wrong scope -> Forbidden
        let res = check_scope(Some(&ctx), "project-a", None, Scope::Delete);
        assert!(res.is_err());
        assert_eq!(res.unwrap_err().0, StatusCode::FORBIDDEN);

        // Different project -> Forbidden
        let res = check_scope(Some(&ctx), "project-b", None, Scope::Read);
        assert!(res.is_err());
        assert_eq!(res.unwrap_err().0, StatusCode::FORBIDDEN);
    }

    #[test]
    fn test_check_scope_global_admin() {
        let key = ApiKey::new(
            "k1".to_string(),
            "admin".to_string(),
            "any-project".to_string(),
            Role::Admin,
        );
        let ctx = AuthContext {
            api_key: key,
            source_ip: None,
        };

        // Global admin can access ANY project
        assert!(check_scope(Some(&ctx), "project-a", None, Scope::Read).is_ok());
        assert!(check_scope(Some(&ctx), "project-b", None, Scope::Delete).is_ok());
        assert!(check_scope(Some(&ctx), "other", None, Scope::Admin).is_ok());
    }

    #[test]
    fn test_check_scope_benchmark_restriction() {
        let mut key = ApiKey::new(
            "k1".to_string(),
            "n1".to_string(),
            "project-a".to_string(),
            Role::Contributor,
        );
        key.benchmark_regex = Some("^web-.*$".to_string());

        let ctx = AuthContext {
            api_key: key,
            source_ip: None,
        };

        // Matches regex -> OK
        assert!(check_scope(Some(&ctx), "project-a", Some("web-auth"), Scope::Read).is_ok());
        assert!(check_scope(Some(&ctx), "project-a", Some("web-api"), Scope::Write).is_ok());

        // Does not match regex -> Forbidden
        let res = check_scope(Some(&ctx), "project-a", Some("worker-job"), Scope::Read);
        assert!(res.is_err());
        assert_eq!(res.unwrap_err().0, StatusCode::FORBIDDEN);

        // No benchmark name provided (e.g. list operation) -> OK (scoping only applies to explicit access)
        assert!(check_scope(Some(&ctx), "project-a", None, Scope::Read).is_ok());
    }
}