mockforge-registry-core 0.3.137

Shared domain models, storage abstractions, and OSS-safe handlers for MockForge's registry backends (SaaS Postgres + OSS SQLite admin UI).
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
//! Error types for the registry core.
//!
//! These were originally defined inside `mockforge-registry-server`. They
//! live here so both the SaaS binary and the OSS admin server can share the
//! same `ApiError` / `StoreError` types and the same `IntoResponse`
//! implementation.
//!
//! All error responses include a `request_id` field for correlation and
//! debugging. The request_id is extracted from the current tracing span
//! (set by the request_id middleware in the consuming binary).

use axum::{
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use serde_json::json;
use thiserror::Error;
use tracing::Span;

// ---------------------------------------------------------------------------
// StoreError — returned by every `RegistryStore` method
// ---------------------------------------------------------------------------

/// Result alias for all [`crate::store::RegistryStore`] operations.
pub type StoreResult<T> = Result<T, StoreError>;

/// Backend-agnostic errors surfaced by `RegistryStore` implementations.
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    #[error("record not found")]
    NotFound,

    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("hashing error: {0}")]
    Hash(String),
}

// ---------------------------------------------------------------------------
// ApiError — returned by every HTTP handler
// ---------------------------------------------------------------------------

/// Get the current request ID from the tracing span
fn get_request_id() -> String {
    Span::current()
        .field("request_id")
        .map(|f| f.to_string())
        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
}

#[derive(Error, Debug)]
pub enum ApiError {
    // Resource not found errors
    #[error("Plugin not found: {0}")]
    PluginNotFound(String),

    #[error("Template not found: {0}")]
    TemplateNotFound(String),

    #[error("Scenario not found: {0}")]
    ScenarioNotFound(String),

    #[error("Version not found: {0}")]
    InvalidVersion(String),

    // Resource conflict errors
    #[error("Plugin already exists: {0}")]
    PluginExists(String),

    #[error("Template already exists: {0}")]
    TemplateExists(String),

    #[error("Scenario already exists: {0}")]
    ScenarioExists(String),

    /// Generic resource-state conflict — maps to 409 CONFLICT. Use this
    /// when an action is rejected because the resource is already in the
    /// requested terminal state (e.g. double-revoke) and the typed
    /// `*Exists` variants don't apply.
    #[error("Conflict: {0}")]
    Conflict(String),

    // Authentication and authorization errors
    #[error("Authentication required")]
    AuthRequired,

    #[error("Permission denied")]
    PermissionDenied,

    #[error("Insufficient scope: required '{required}', token has [{scopes:?}]")]
    InsufficientScope {
        required: String,
        scopes: Vec<String>,
    },

    #[error("Organization not found or access denied")]
    OrganizationNotFound,

    // Validation errors
    #[error("Invalid request: {0}")]
    InvalidRequest(String),

    #[error("Validation failed: {0}")]
    ValidationFailed(String),

    // Rate limiting
    #[error("Rate limit exceeded: {0}")]
    RateLimitExceeded(String),

    /// Plan-quota exhaustion (#449). Distinct from `RateLimitExceeded` (which
    /// is per-IP/global throttling) and `ResourceLimitExceeded` (which is
    /// soft caps on entity counts). This carries the structured numbers the
    /// client needs to render an upsell: which limit, how much used, what's
    /// the cap, and the rolling window key.
    #[error("Usage limit exceeded: {limit_type} {current}/{max}")]
    UsageLimitExceeded {
        limit_type: String,
        current: i64,
        max: i64,
        period: String,
    },

    // Resource limit errors
    #[error("Resource limit exceeded: {0}")]
    ResourceLimitExceeded(String),

    /// Subscription is past_due (#449 / criterion 8). Maps to 402 so clients
    /// can distinguish "your card failed, fix billing" from "you don't have
    /// permission" (403) or "this resource doesn't exist" (404).
    #[error("Payment required: {0}")]
    PaymentRequired(String),

    // Storage and database errors
    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("Storage error: {0}")]
    Storage(String),

    // Internal errors
    #[error("Internal server error")]
    Internal(#[from] anyhow::Error),
}

impl From<StoreError> for ApiError {
    fn from(e: StoreError) -> Self {
        match e {
            StoreError::NotFound => ApiError::InvalidRequest("Not found".to_string()),
            StoreError::Database(err) => ApiError::Database(err),
            StoreError::Hash(msg) => ApiError::Storage(format!("hash error: {}", msg)),
        }
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, error_code, error_message, details) = match self {
            // Resource not found errors (404)
            ApiError::PluginNotFound(name) => (
                StatusCode::NOT_FOUND,
                "PLUGIN_NOT_FOUND",
                format!("Plugin '{}' not found", name),
                json!({
                    "resource": "plugin",
                    "name": name
                }),
            ),
            ApiError::TemplateNotFound(name) => (
                StatusCode::NOT_FOUND,
                "TEMPLATE_NOT_FOUND",
                format!("Template '{}' not found", name),
                json!({
                    "resource": "template",
                    "name": name
                }),
            ),
            ApiError::ScenarioNotFound(name) => (
                StatusCode::NOT_FOUND,
                "SCENARIO_NOT_FOUND",
                format!("Scenario '{}' not found", name),
                json!({
                    "resource": "scenario",
                    "name": name
                }),
            ),
            ApiError::InvalidVersion(ver) => (
                StatusCode::NOT_FOUND,
                "VERSION_NOT_FOUND",
                format!("Version '{}' not found", ver),
                json!({
                    "version": ver
                }),
            ),

            // Resource conflict errors (409)
            ApiError::PluginExists(name) => (
                StatusCode::CONFLICT,
                "PLUGIN_EXISTS",
                format!("Plugin '{}' already exists", name),
                json!({
                    "resource": "plugin",
                    "name": name
                }),
            ),
            ApiError::TemplateExists(name) => (
                StatusCode::CONFLICT,
                "TEMPLATE_EXISTS",
                format!("Template '{}' already exists", name),
                json!({
                    "resource": "template",
                    "name": name
                }),
            ),
            ApiError::ScenarioExists(name) => (
                StatusCode::CONFLICT,
                "SCENARIO_EXISTS",
                format!("Scenario '{}' already exists", name),
                json!({
                    "resource": "scenario",
                    "name": name
                }),
            ),
            ApiError::Conflict(msg) => (
                StatusCode::CONFLICT,
                "CONFLICT",
                msg.clone(),
                json!({
                    "message": msg
                }),
            ),

            // Authentication and authorization errors
            ApiError::AuthRequired => (
                StatusCode::UNAUTHORIZED,
                "AUTH_REQUIRED",
                "Authentication required".to_string(),
                json!({
                    "hint": "Include a valid Authorization header with your request"
                }),
            ),
            ApiError::PermissionDenied => (
                StatusCode::FORBIDDEN,
                "PERMISSION_DENIED",
                "Permission denied".to_string(),
                json!({
                    "hint": "You don't have permission to perform this action"
                }),
            ),
            ApiError::OrganizationNotFound => (
                StatusCode::NOT_FOUND,
                "ORGANIZATION_NOT_FOUND",
                "Organization not found or access denied".to_string(),
                json!({
                    "hint": "Check that the organization exists and you have access to it"
                }),
            ),
            ApiError::InsufficientScope { required, scopes } => (
                StatusCode::FORBIDDEN,
                "INSUFFICIENT_SCOPE",
                format!(
                    "Insufficient scope: required '{}', token has [{}]",
                    required,
                    scopes.join(", ")
                ),
                json!({
                    "required_scope": required,
                    "token_scopes": scopes,
                    "hint": "Your API token does not have the required scope for this operation. Create a new token with the appropriate scope."
                }),
            ),

            // Validation errors (400)
            ApiError::InvalidRequest(msg) => (
                StatusCode::BAD_REQUEST,
                "INVALID_REQUEST",
                msg.clone(),
                json!({
                    "message": msg
                }),
            ),
            ApiError::ValidationFailed(msg) => (
                StatusCode::BAD_REQUEST,
                "VALIDATION_FAILED",
                format!("Validation failed: {}", msg),
                json!({
                    "message": msg
                }),
            ),

            // Rate limiting (429) - handled specially to include Retry-After header
            ApiError::RateLimitExceeded(msg) => {
                tracing::warn!("Rate limit exceeded: {}", msg);
                let request_id = get_request_id();
                let body = Json(json!({
                    "error": format!("Rate limit exceeded: {}", msg),
                    "error_code": "RATE_LIMIT_EXCEEDED",
                    "status": 429,
                    "request_id": request_id,
                    "details": {
                        "message": msg,
                        "hint": "Please wait before making more requests or upgrade your plan",
                        "retry_after_seconds": 60
                    }
                }));
                return (StatusCode::TOO_MANY_REQUESTS, [(header::RETRY_AFTER, "60")], body)
                    .into_response();
            }

            // Resource limits (403)
            ApiError::ResourceLimitExceeded(msg) => {
                tracing::warn!("Resource limit exceeded: {}", msg);
                (
                    StatusCode::FORBIDDEN,
                    "RESOURCE_LIMIT_EXCEEDED",
                    format!("Resource limit exceeded: {}", msg),
                    json!({
                        "message": msg,
                        "hint": "Upgrade your plan to increase limits"
                    }),
                )
            }

            // Usage-quota exhaustion (#449) — 429 + retry-after, with the
            // structured numbers the dashboard needs to render an upsell.
            ApiError::UsageLimitExceeded {
                limit_type,
                current,
                max,
                period,
            } => {
                tracing::warn!(
                    limit = %limit_type,
                    current,
                    max,
                    period = %period,
                    "Usage limit exceeded"
                );
                let request_id = get_request_id();
                let body = Json(json!({
                    "error": "usage_limit_exceeded",
                    "error_code": "USAGE_LIMIT_EXCEEDED",
                    "status": 429,
                    "request_id": request_id,
                    "limit": limit_type,
                    "current": current,
                    "max": max,
                    "details": {
                        "period": period,
                        "hint": "Upgrade your plan or wait for the next billing period",
                        "upgrade_url": "/billing/upgrade"
                    }
                }));
                return (StatusCode::TOO_MANY_REQUESTS, [(header::RETRY_AFTER, "60")], body)
                    .into_response();
            }

            // Subscription past_due (#449 criterion 8) — 402 PaymentRequired.
            ApiError::PaymentRequired(msg) => {
                tracing::warn!("Payment required: {}", msg);
                (
                    StatusCode::PAYMENT_REQUIRED,
                    "PAYMENT_REQUIRED",
                    msg.clone(),
                    json!({
                        "message": msg,
                        "hint": "Update your payment method in the billing portal",
                        "billing_url": "/billing"
                    }),
                )
            }

            // Storage and database errors (500)
            ApiError::Database(e) => {
                tracing::error!("Database error: {:?}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "DATABASE_ERROR",
                    "Database error occurred".to_string(),
                    json!({
                        "hint": "Please try again later or contact support if the problem persists"
                    }),
                )
            }
            ApiError::Storage(msg) => {
                tracing::error!("Storage error: {}", msg);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "STORAGE_ERROR",
                    format!("Storage error: {}", msg),
                    json!({
                        "message": msg,
                        "hint": "Please try again later or contact support if the problem persists"
                    }),
                )
            }

            // Internal errors (500)
            ApiError::Internal(e) => {
                tracing::error!("Internal error: {:?}", e);
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "INTERNAL_ERROR",
                    "Internal server error".to_string(),
                    json!({
                        "hint": "Please try again later or contact support if the problem persists"
                    }),
                )
            }
        };

        let request_id = get_request_id();
        let body = Json(json!({
            "error": error_message,
            "error_code": error_code,
            "status": status.as_u16(),
            "request_id": request_id,
            "details": details
        }));

        (status, body).into_response()
    }
}

pub type ApiResult<T> = Result<T, ApiError>;

#[cfg(test)]
mod tests {
    use super::*;
    use axum::response::IntoResponse;

    // ApiError variant tests
    #[test]
    fn test_api_error_plugin_not_found() {
        let error = ApiError::PluginNotFound("test-plugin".to_string());
        assert_eq!(error.to_string(), "Plugin not found: test-plugin");
    }

    #[test]
    fn test_api_error_template_not_found() {
        let error = ApiError::TemplateNotFound("test-template".to_string());
        assert_eq!(error.to_string(), "Template not found: test-template");
    }

    #[test]
    fn test_api_error_scenario_not_found() {
        let error = ApiError::ScenarioNotFound("test-scenario".to_string());
        assert_eq!(error.to_string(), "Scenario not found: test-scenario");
    }

    #[test]
    fn test_api_error_invalid_version() {
        let error = ApiError::InvalidVersion("1.0.0".to_string());
        assert_eq!(error.to_string(), "Version not found: 1.0.0");
    }

    #[test]
    fn test_api_error_plugin_exists() {
        let error = ApiError::PluginExists("test-plugin".to_string());
        assert_eq!(error.to_string(), "Plugin already exists: test-plugin");
    }

    #[test]
    fn test_api_error_template_exists() {
        let error = ApiError::TemplateExists("test-template".to_string());
        assert_eq!(error.to_string(), "Template already exists: test-template");
    }

    #[test]
    fn test_api_error_scenario_exists() {
        let error = ApiError::ScenarioExists("test-scenario".to_string());
        assert_eq!(error.to_string(), "Scenario already exists: test-scenario");
    }

    #[test]
    fn test_api_error_auth_required() {
        let error = ApiError::AuthRequired;
        assert_eq!(error.to_string(), "Authentication required");
    }

    #[test]
    fn test_api_error_permission_denied() {
        let error = ApiError::PermissionDenied;
        assert_eq!(error.to_string(), "Permission denied");
    }

    #[test]
    fn test_api_error_organization_not_found() {
        let error = ApiError::OrganizationNotFound;
        assert_eq!(error.to_string(), "Organization not found or access denied");
    }

    #[test]
    fn test_api_error_invalid_request() {
        let error = ApiError::InvalidRequest("Bad input".to_string());
        assert_eq!(error.to_string(), "Invalid request: Bad input");
    }

    #[test]
    fn test_api_error_validation_failed() {
        let error = ApiError::ValidationFailed("Name is required".to_string());
        assert_eq!(error.to_string(), "Validation failed: Name is required");
    }

    #[test]
    fn test_api_error_rate_limit_exceeded() {
        let error = ApiError::RateLimitExceeded("100 requests/minute".to_string());
        assert_eq!(error.to_string(), "Rate limit exceeded: 100 requests/minute");
    }

    #[test]
    fn test_api_error_resource_limit_exceeded() {
        let error = ApiError::ResourceLimitExceeded("10 plugins".to_string());
        assert_eq!(error.to_string(), "Resource limit exceeded: 10 plugins");
    }

    #[test]
    fn test_api_error_storage() {
        let error = ApiError::Storage("S3 connection failed".to_string());
        assert_eq!(error.to_string(), "Storage error: S3 connection failed");
    }

    #[test]
    fn test_api_error_internal() {
        let error = ApiError::Internal(anyhow::anyhow!("Unknown error"));
        assert_eq!(error.to_string(), "Internal server error");
    }

    #[test]
    fn test_store_error_not_found_converts_to_api_error() {
        let se = StoreError::NotFound;
        let ae: ApiError = se.into();
        assert!(matches!(ae, ApiError::InvalidRequest(_)));
    }

    // IntoResponse tests - check status codes
    #[tokio::test]
    async fn test_into_response_plugin_not_found() {
        let error = ApiError::PluginNotFound("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_template_not_found() {
        let error = ApiError::TemplateNotFound("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_scenario_not_found() {
        let error = ApiError::ScenarioNotFound("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_invalid_version() {
        let error = ApiError::InvalidVersion("1.0.0".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_plugin_exists() {
        let error = ApiError::PluginExists("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn test_into_response_template_exists() {
        let error = ApiError::TemplateExists("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn test_into_response_scenario_exists() {
        let error = ApiError::ScenarioExists("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::CONFLICT);
    }

    #[test]
    fn test_api_error_conflict() {
        let error = ApiError::Conflict("Trust root is already revoked".to_string());
        assert_eq!(error.to_string(), "Conflict: Trust root is already revoked");
    }

    #[tokio::test]
    async fn test_into_response_conflict() {
        let error = ApiError::Conflict("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn test_into_response_auth_required() {
        let error = ApiError::AuthRequired;
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_into_response_permission_denied() {
        let error = ApiError::PermissionDenied;
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_into_response_organization_not_found() {
        let error = ApiError::OrganizationNotFound;
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_invalid_request() {
        let error = ApiError::InvalidRequest("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_into_response_validation_failed() {
        let error = ApiError::ValidationFailed("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_into_response_rate_limit_exceeded() {
        let error = ApiError::RateLimitExceeded("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(
            response.headers().get(header::RETRY_AFTER).map(|v| v.to_str().unwrap()),
            Some("60")
        );
    }

    #[tokio::test]
    async fn test_into_response_resource_limit_exceeded() {
        let error = ApiError::ResourceLimitExceeded("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_into_response_usage_limit_exceeded() {
        let error = ApiError::UsageLimitExceeded {
            limit_type: "requests".to_string(),
            current: 250_000,
            max: 250_000,
            period: "2026-05".to_string(),
        };
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(
            response.headers().get(header::RETRY_AFTER).map(|v| v.to_str().unwrap()),
            Some("60")
        );
        let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
        // Spec from #449 acceptance criterion 1.
        assert_eq!(body["error"], "usage_limit_exceeded");
        assert_eq!(body["limit"], "requests");
        assert_eq!(body["current"], 250_000);
        assert_eq!(body["max"], 250_000);
    }

    #[tokio::test]
    async fn test_into_response_payment_required() {
        let error = ApiError::PaymentRequired("Subscription past due".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);
    }

    #[tokio::test]
    async fn test_into_response_storage() {
        let error = ApiError::Storage("test".to_string());
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_into_response_internal() {
        let error = ApiError::Internal(anyhow::anyhow!("test"));
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_api_error_debug() {
        let error = ApiError::AuthRequired;
        let debug = format!("{:?}", error);
        assert!(debug.contains("AuthRequired"));
    }

    #[test]
    fn test_api_error_insufficient_scope() {
        let error = ApiError::InsufficientScope {
            required: "publish:packages".to_string(),
            scopes: vec!["read:packages".to_string()],
        };
        assert!(error.to_string().contains("publish:packages"));
        assert!(error.to_string().contains("read:packages"));
    }

    #[tokio::test]
    async fn test_into_response_insufficient_scope() {
        let error = ApiError::InsufficientScope {
            required: "publish:packages".to_string(),
            scopes: vec!["read:packages".to_string()],
        };
        let response = error.into_response();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }
}