netviper-talos 0.2.4

A Rust-based secure licensing system.
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! API Token management for Talos service authentication.
//!
//! This module provides database-backed token management for API authentication.
//! Tokens are stored as SHA-256 hashes in the database, and the raw token is only
//! returned once at creation time.
//!
//! # Usage
//!
//! ```rust,ignore
//! use talos::server::tokens::{ApiToken, TokenManager};
//!
//! // Create a new token
//! let (token, raw) = manager.create_token("My Service", &["licenses:read"]).await?;
//! println!("Save this token: {}", raw); // Only shown once!
//!
//! // Validate a token from a request
//! let token = manager.validate_token(&raw_token).await?;
//! if token.has_scope("licenses:read") {
//!     // Allow the request
//! }
//! ```

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use chrono::{NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sqlx::{query, FromRow};
use tracing::{info, warn};
use uuid::Uuid;

#[cfg(feature = "openapi")]
use utoipa::ToSchema;

use crate::errors::{LicenseError, LicenseResult};
use crate::server::database::Database;
use crate::server::handlers::AppState;

/// API Token stored in the database.
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ApiToken {
    /// Unique identifier for the token
    pub id: String,
    /// Human-readable name for the token
    pub name: String,
    /// SHA-256 hash of the token (never store raw tokens)
    #[serde(skip_serializing)]
    pub token_hash: String,
    /// Space-separated list of scopes
    pub scopes: String,
    /// When the token was created
    pub created_at: NaiveDateTime,
    /// When the token expires (None = never)
    pub expires_at: Option<NaiveDateTime>,
    /// Last time the token was used
    pub last_used_at: Option<NaiveDateTime>,
    /// When the token was revoked (None = active)
    pub revoked_at: Option<NaiveDateTime>,
    /// Who created this token
    pub created_by: Option<String>,
}

impl ApiToken {
    /// Check if the token has a specific scope.
    pub fn has_scope(&self, required: &str) -> bool {
        // Check for wildcard scope
        if self.scopes.split_whitespace().any(|s| s == "*") {
            return true;
        }

        // Check for exact match or category wildcard
        for scope in self.scopes.split_whitespace() {
            if scope == required {
                return true;
            }
            // Check for wildcard match: "licenses:*" matches "licenses:read"
            if let Some(prefix) = scope.strip_suffix(":*") {
                if required.starts_with(prefix) && required.chars().nth(prefix.len()) == Some(':') {
                    return true;
                }
            }
        }

        false
    }

    /// Check if the token is valid (not expired, not revoked).
    pub fn is_valid(&self) -> bool {
        // Check if revoked
        if self.revoked_at.is_some() {
            return false;
        }

        // Check if expired
        if let Some(expires_at) = self.expires_at {
            if Utc::now().naive_utc() > expires_at {
                return false;
            }
        }

        true
    }

    /// Get the scopes as a vector.
    pub fn scope_list(&self) -> Vec<String> {
        self.scopes.split_whitespace().map(String::from).collect()
    }
}

/// Response for token creation (includes the raw token).
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct CreateTokenResponse {
    /// The created token metadata
    pub token: TokenMetadata,
    /// The raw token value - ONLY RETURNED ONCE
    pub raw_token: String,
}

/// Token metadata for listing (excludes hash and raw token).
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct TokenMetadata {
    pub id: String,
    pub name: String,
    pub scopes: Vec<String>,
    pub created_at: String,
    pub expires_at: Option<String>,
    pub last_used_at: Option<String>,
    pub revoked_at: Option<String>,
    pub created_by: Option<String>,
    pub is_active: bool,
}

impl From<ApiToken> for TokenMetadata {
    fn from(token: ApiToken) -> Self {
        let is_active = token.is_valid();
        let scopes = token.scope_list();
        TokenMetadata {
            id: token.id,
            name: token.name,
            scopes,
            created_at: token.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            expires_at: token
                .expires_at
                .map(|t| t.format("%Y-%m-%dT%H:%M:%SZ").to_string()),
            last_used_at: token
                .last_used_at
                .map(|t| t.format("%Y-%m-%dT%H:%M:%SZ").to_string()),
            revoked_at: token
                .revoked_at
                .map(|t| t.format("%Y-%m-%dT%H:%M:%SZ").to_string()),
            created_by: token.created_by,
            is_active,
        }
    }
}

/// Request to create a new API token.
#[derive(Debug, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct CreateTokenRequest {
    /// Human-readable name for the token
    pub name: String,
    /// Space-separated or array of scopes
    pub scopes: Vec<String>,
    /// Optional expiration (ISO 8601 format)
    pub expires_at: Option<String>,
}

/// Generate a secure random token.
fn generate_raw_token() -> String {
    // Generate a UUID-based token with prefix for easy identification
    format!("talos_{}", Uuid::new_v4().to_string().replace('-', ""))
}

/// Hash a token using SHA-256.
fn hash_token(raw_token: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(raw_token.as_bytes());
    format!("{:x}", hasher.finalize())
}

impl Database {
    /// Create a new API token.
    ///
    /// Returns the token metadata and the raw token value (only returned once).
    pub async fn create_api_token(
        &self,
        name: &str,
        scopes: &[&str],
        expires_at: Option<NaiveDateTime>,
        created_by: Option<&str>,
    ) -> LicenseResult<(ApiToken, String)> {
        let id = Uuid::new_v4().to_string();
        let raw_token = generate_raw_token();
        let token_hash = hash_token(&raw_token);
        let now = Utc::now().naive_utc();
        let scopes_str = scopes.join(" ");

        let token = ApiToken {
            id: id.clone(),
            name: name.to_string(),
            token_hash: token_hash.clone(),
            scopes: scopes_str.clone(),
            created_at: now,
            expires_at,
            last_used_at: None,
            revoked_at: None,
            created_by: created_by.map(String::from),
        };

        match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => {
                query(
                    "INSERT INTO api_tokens (id, name, token_hash, scopes, created_at, expires_at, created_by) \
                     VALUES (?, ?, ?, ?, ?, ?, ?)",
                )
                .bind(&id)
                .bind(name)
                .bind(&token_hash)
                .bind(&scopes_str)
                .bind(now)
                .bind(expires_at)
                .bind(created_by)
                .execute(pool)
                .await
                .map_err(|e| LicenseError::ServerError(format!("failed to create token: {e}")))?;
            }
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => {
                query(
                    "INSERT INTO api_tokens (id, name, token_hash, scopes, created_at, expires_at, created_by) \
                     VALUES ($1, $2, $3, $4, $5, $6, $7)",
                )
                .bind(&id)
                .bind(name)
                .bind(&token_hash)
                .bind(&scopes_str)
                .bind(now)
                .bind(expires_at)
                .bind(created_by)
                .execute(pool)
                .await
                .map_err(|e| LicenseError::ServerError(format!("failed to create token: {e}")))?;
            }
        }

        info!("Created API token '{}' with id={}", name, id);
        Ok((token, raw_token))
    }

    /// Validate a raw token and return the token if valid.
    ///
    /// Also updates `last_used_at` timestamp.
    pub async fn validate_api_token(&self, raw_token: &str) -> LicenseResult<Option<ApiToken>> {
        let token_hash = hash_token(raw_token);

        let token: Option<ApiToken> = match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens WHERE token_hash = ?",
            )
            .bind(&token_hash)
            .fetch_optional(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("token lookup failed: {e}")))?,
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens WHERE token_hash = $1",
            )
            .bind(&token_hash)
            .fetch_optional(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("token lookup failed: {e}")))?,
        };

        if let Some(ref t) = token {
            if t.is_valid() {
                // Update last_used_at
                self.update_token_last_used(&t.id).await?;
            }
        }

        Ok(token)
    }

    /// Update the last_used_at timestamp for a token.
    async fn update_token_last_used(&self, token_id: &str) -> LicenseResult<()> {
        let now = Utc::now().naive_utc();

        match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => {
                query("UPDATE api_tokens SET last_used_at = ? WHERE id = ?")
                    .bind(now)
                    .bind(token_id)
                    .execute(pool)
                    .await
                    .map_err(|e| {
                        LicenseError::ServerError(format!("update last_used failed: {e}"))
                    })?;
            }
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => {
                query("UPDATE api_tokens SET last_used_at = $1 WHERE id = $2")
                    .bind(now)
                    .bind(token_id)
                    .execute(pool)
                    .await
                    .map_err(|e| {
                        LicenseError::ServerError(format!("update last_used failed: {e}"))
                    })?;
            }
        }

        Ok(())
    }

    /// List all API tokens (metadata only, no hashes).
    pub async fn list_api_tokens(&self) -> LicenseResult<Vec<ApiToken>> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens ORDER BY created_at DESC",
            )
            .fetch_all(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("list tokens failed: {e}"))),
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens ORDER BY created_at DESC",
            )
            .fetch_all(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("list tokens failed: {e}"))),
        }
    }

    /// Get a token by ID.
    pub async fn get_api_token(&self, token_id: &str) -> LicenseResult<Option<ApiToken>> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens WHERE id = ?",
            )
            .bind(token_id)
            .fetch_optional(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("get token failed: {e}"))),
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => sqlx::query_as::<_, ApiToken>(
                "SELECT id, name, token_hash, scopes, created_at, expires_at, \
                            last_used_at, revoked_at, created_by \
                     FROM api_tokens WHERE id = $1",
            )
            .bind(token_id)
            .fetch_optional(pool)
            .await
            .map_err(|e| LicenseError::ServerError(format!("get token failed: {e}"))),
        }
    }

    /// Revoke a token by ID.
    pub async fn revoke_api_token(&self, token_id: &str) -> LicenseResult<bool> {
        let now = Utc::now().naive_utc();

        let rows_affected = match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => {
                query("UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL")
                    .bind(now)
                    .bind(token_id)
                    .execute(pool)
                    .await
                    .map_err(|e| LicenseError::ServerError(format!("revoke token failed: {e}")))?
                    .rows_affected()
            }
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => {
                query("UPDATE api_tokens SET revoked_at = $1 WHERE id = $2 AND revoked_at IS NULL")
                    .bind(now)
                    .bind(token_id)
                    .execute(pool)
                    .await
                    .map_err(|e| LicenseError::ServerError(format!("revoke token failed: {e}")))?
                    .rows_affected()
            }
        };

        if rows_affected > 0 {
            warn!("Revoked API token id={}", token_id);
        }

        Ok(rows_affected > 0)
    }

    /// Check if any API tokens exist in the database.
    pub async fn has_api_tokens(&self) -> LicenseResult<bool> {
        match self {
            #[cfg(feature = "sqlite")]
            Database::SQLite(pool) => {
                let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM api_tokens")
                    .fetch_one(pool)
                    .await
                    .map_err(|e| LicenseError::ServerError(format!("count tokens failed: {e}")))?;
                Ok(count.0 > 0)
            }
            #[cfg(feature = "postgres")]
            Database::Postgres(pool) => {
                let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM api_tokens")
                    .fetch_one(pool)
                    .await
                    .map_err(|e| LicenseError::ServerError(format!("count tokens failed: {e}")))?;
                Ok(count.0 > 0)
            }
        }
    }
}

// ============================================================================
// HTTP Handlers for Token Management
// ============================================================================

/// Response for token list endpoint.
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ListTokensResponse {
    pub tokens: Vec<TokenMetadata>,
}

/// Response for single token operations.
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct TokenResponse {
    pub token: TokenMetadata,
}

/// Response for token revocation.
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct RevokeTokenResponse {
    pub success: bool,
    pub message: String,
}

/// Error response for token operations.
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct TokenErrorResponse {
    pub error: String,
    pub code: String,
}

impl TokenErrorResponse {
    fn new(error: impl Into<String>, code: impl Into<String>) -> Self {
        Self {
            error: error.into(),
            code: code.into(),
        }
    }
}

/// POST /api/v1/tokens - Create a new API token.
///
/// Request body: `CreateTokenRequest`
/// Response: `CreateTokenResponse` (includes raw token, only shown once)
#[cfg_attr(feature = "openapi", utoipa::path(
    post,
    path = "/api/v1/tokens",
    tag = "tokens",
    request_body = CreateTokenRequest,
    responses(
        (status = 201, description = "Token created", body = CreateTokenResponse),
        (status = 400, description = "Invalid request", body = TokenErrorResponse),
        (status = 500, description = "Server error", body = TokenErrorResponse),
    ),
    security(("bearer_auth" = []))
))]
pub async fn create_token_handler(
    State(state): State<AppState>,
    Json(req): Json<CreateTokenRequest>,
) -> impl IntoResponse {
    // Validate request
    if req.name.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!(TokenErrorResponse::new(
                "Token name is required",
                "INVALID_NAME"
            ))),
        )
            .into_response();
    }

    if req.scopes.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!(TokenErrorResponse::new(
                "At least one scope is required",
                "INVALID_SCOPES"
            ))),
        )
            .into_response();
    }

    // Parse optional expiration
    let expires_at = match &req.expires_at {
        Some(exp_str) => match NaiveDateTime::parse_from_str(exp_str, "%Y-%m-%dT%H:%M:%SZ") {
            Ok(dt) => Some(dt),
            Err(_) => match NaiveDateTime::parse_from_str(exp_str, "%Y-%m-%dT%H:%M:%S") {
                Ok(dt) => Some(dt),
                Err(_) => {
                    return (
                        StatusCode::BAD_REQUEST,
                        Json(serde_json::json!(TokenErrorResponse::new(
                            "Invalid expires_at format. Use ISO 8601 format.",
                            "INVALID_EXPIRATION"
                        ))),
                    )
                        .into_response();
                }
            },
        },
        None => None,
    };

    // Convert scopes to &str slice
    let scope_refs: Vec<&str> = req.scopes.iter().map(|s| s.as_str()).collect();

    // Create the token
    match state
        .db
        .create_api_token(&req.name, &scope_refs, expires_at, None)
        .await
    {
        Ok((token, raw_token)) => {
            let response = CreateTokenResponse {
                token: TokenMetadata::from(token),
                raw_token,
            };
            (StatusCode::CREATED, Json(serde_json::json!(response))).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!(TokenErrorResponse::new(
                format!("Failed to create token: {}", e),
                "CREATE_FAILED"
            ))),
        )
            .into_response(),
    }
}

/// GET /api/v1/tokens - List all API tokens.
///
/// Response: `ListTokensResponse`
#[cfg_attr(feature = "openapi", utoipa::path(
    get,
    path = "/api/v1/tokens",
    tag = "tokens",
    responses(
        (status = 200, description = "List of tokens", body = ListTokensResponse),
        (status = 500, description = "Server error", body = TokenErrorResponse),
    ),
    security(("bearer_auth" = []))
))]
pub async fn list_tokens_handler(State(state): State<AppState>) -> impl IntoResponse {
    match state.db.list_api_tokens().await {
        Ok(tokens) => {
            let metadata: Vec<TokenMetadata> =
                tokens.into_iter().map(TokenMetadata::from).collect();
            let response = ListTokensResponse { tokens: metadata };
            (StatusCode::OK, Json(serde_json::json!(response))).into_response()
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!(TokenErrorResponse::new(
                format!("Failed to list tokens: {}", e),
                "LIST_FAILED"
            ))),
        )
            .into_response(),
    }
}

/// GET /api/v1/tokens/:id - Get a specific token by ID.
///
/// Response: `TokenResponse`
#[cfg_attr(feature = "openapi", utoipa::path(
    get,
    path = "/api/v1/tokens/{id}",
    tag = "tokens",
    params(
        ("id" = String, Path, description = "Token ID")
    ),
    responses(
        (status = 200, description = "Token details", body = TokenResponse),
        (status = 404, description = "Token not found", body = TokenErrorResponse),
        (status = 500, description = "Server error", body = TokenErrorResponse),
    ),
    security(("bearer_auth" = []))
))]
pub async fn get_token_handler(
    State(state): State<AppState>,
    Path(token_id): Path<String>,
) -> impl IntoResponse {
    match state.db.get_api_token(&token_id).await {
        Ok(Some(token)) => {
            let response = TokenResponse {
                token: TokenMetadata::from(token),
            };
            (StatusCode::OK, Json(serde_json::json!(response))).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!(TokenErrorResponse::new(
                "Token not found",
                "NOT_FOUND"
            ))),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!(TokenErrorResponse::new(
                format!("Failed to get token: {}", e),
                "GET_FAILED"
            ))),
        )
            .into_response(),
    }
}

/// DELETE /api/v1/tokens/:id - Revoke a token.
///
/// Response: `RevokeTokenResponse`
#[cfg_attr(feature = "openapi", utoipa::path(
    delete,
    path = "/api/v1/tokens/{id}",
    tag = "tokens",
    params(
        ("id" = String, Path, description = "Token ID")
    ),
    responses(
        (status = 200, description = "Token revoked", body = RevokeTokenResponse),
        (status = 404, description = "Token not found", body = TokenErrorResponse),
        (status = 500, description = "Server error", body = TokenErrorResponse),
    ),
    security(("bearer_auth" = []))
))]
pub async fn revoke_token_handler(
    State(state): State<AppState>,
    Path(token_id): Path<String>,
) -> impl IntoResponse {
    match state.db.revoke_api_token(&token_id).await {
        Ok(true) => {
            let response = RevokeTokenResponse {
                success: true,
                message: "Token revoked successfully".to_string(),
            };
            (StatusCode::OK, Json(serde_json::json!(response))).into_response()
        }
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!(TokenErrorResponse::new(
                "Token not found or already revoked",
                "NOT_FOUND"
            ))),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!(TokenErrorResponse::new(
                format!("Failed to revoke token: {}", e),
                "REVOKE_FAILED"
            ))),
        )
            .into_response(),
    }
}

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

    #[test]
    fn token_has_scope_exact_match() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "licenses:read licenses:write".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: None,
            last_used_at: None,
            revoked_at: None,
            created_by: None,
        };

        assert!(token.has_scope("licenses:read"));
        assert!(token.has_scope("licenses:write"));
        assert!(!token.has_scope("licenses:delete"));
        assert!(!token.has_scope("admin:read"));
    }

    #[test]
    fn token_has_scope_wildcard() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "*".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: None,
            last_used_at: None,
            revoked_at: None,
            created_by: None,
        };

        assert!(token.has_scope("licenses:read"));
        assert!(token.has_scope("anything:here"));
    }

    #[test]
    fn token_has_scope_category_wildcard() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "licenses:*".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: None,
            last_used_at: None,
            revoked_at: None,
            created_by: None,
        };

        assert!(token.has_scope("licenses:read"));
        assert!(token.has_scope("licenses:write"));
        assert!(token.has_scope("licenses:delete"));
        assert!(!token.has_scope("admin:read"));
    }

    #[test]
    fn token_is_valid_active() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "*".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: None,
            last_used_at: None,
            revoked_at: None,
            created_by: None,
        };

        assert!(token.is_valid());
    }

    #[test]
    fn token_is_valid_revoked() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "*".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: None,
            last_used_at: None,
            revoked_at: Some(Utc::now().naive_utc()),
            created_by: None,
        };

        assert!(!token.is_valid());
    }

    #[test]
    fn token_is_valid_expired() {
        let token = ApiToken {
            id: "test".to_string(),
            name: "Test".to_string(),
            token_hash: "hash".to_string(),
            scopes: "*".to_string(),
            created_at: Utc::now().naive_utc(),
            expires_at: Some(Utc::now().naive_utc() - chrono::Duration::hours(1)),
            last_used_at: None,
            revoked_at: None,
            created_by: None,
        };

        assert!(!token.is_valid());
    }

    #[test]
    fn hash_token_produces_sha256() {
        let raw = "talos_abc123";
        let hash = hash_token(raw);
        // SHA-256 produces 64 hex characters
        assert_eq!(hash.len(), 64);
        // Same input should produce same hash
        assert_eq!(hash, hash_token(raw));
        // Different input should produce different hash
        assert_ne!(hash, hash_token("talos_xyz789"));
    }

    #[test]
    fn generate_raw_token_format() {
        let token = generate_raw_token();
        assert!(token.starts_with("talos_"));
        // UUID without dashes = 32 chars, plus "talos_" = 38 chars
        assert_eq!(token.len(), 38);
    }
}