kaccy-db 0.2.0

Database layer for Kaccy Protocol - PostgreSQL, Redis, and distributed caching
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
//! API Key Repository
//!
//! Provides database operations for API key management and authentication.

use crate::error::{DbError, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sqlx::{Executor, PgPool, Postgres};
use uuid::Uuid;

/// API Key record
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct ApiKey {
    /// Unique identifier for the API key.
    pub id: Uuid,
    /// Owner of the API key.
    pub user_id: Uuid,
    /// Bcrypt or Argon2 hash of the full API key value.
    pub key_hash: String,
    /// Short public prefix shown to the user for identification.
    pub key_prefix: String,
    /// Human-readable label for this key.
    pub name: String,
    /// JSON array of permission scopes.
    pub scopes: JsonValue,
    /// Maximum requests allowed per hour, or unlimited if None.
    pub rate_limit_per_hour: Option<i32>,
    /// Timestamp of the most recent use.
    pub last_used_at: Option<DateTime<Utc>>,
    /// Timestamp when the key expires, or None if it never expires.
    pub expires_at: Option<DateTime<Utc>>,
    /// Timestamp when the key was revoked, or None if active.
    pub revoked_at: Option<DateTime<Utc>>,
    /// Record creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Record last-updated timestamp.
    pub updated_at: DateTime<Utc>,
}

/// API Key creation parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateApiKey {
    /// Owner of the new API key.
    pub user_id: Uuid,
    /// Hash of the API key value.
    pub key_hash: String,
    /// Short prefix shown to the user.
    pub key_prefix: String,
    /// Label for the key.
    pub name: String,
    /// List of permission scope strings.
    pub scopes: Vec<String>,
    /// Optional hourly rate limit.
    pub rate_limit_per_hour: Option<i32>,
    /// Optional expiry timestamp.
    pub expires_at: Option<DateTime<Utc>>,
}

/// API Key summary (without sensitive data)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeySummary {
    /// Unique identifier for the key.
    pub id: Uuid,
    /// Short public prefix.
    pub key_prefix: String,
    /// Label for the key.
    pub name: String,
    /// Granted permission scopes.
    pub scopes: Vec<String>,
    /// Optional hourly rate limit.
    pub rate_limit_per_hour: Option<i32>,
    /// Timestamp of the most recent use.
    pub last_used_at: Option<DateTime<Utc>>,
    /// Optional expiry timestamp.
    pub expires_at: Option<DateTime<Utc>>,
    /// Whether the key is currently active (not revoked and not expired).
    pub is_active: bool,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
}

/// Repository for API key operations
pub struct ApiKeyRepository {
    pool: PgPool,
}

impl ApiKeyRepository {
    /// Create a new API key repository
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Create a new API key
    pub async fn create(&self, params: CreateApiKey) -> Result<ApiKey> {
        let scopes_json = serde_json::to_value(&params.scopes)
            .map_err(|e| DbError::Validation(format!("Invalid scopes: {}", e)))?;

        let api_key = sqlx::query_as::<_, ApiKey>(
            r#"
            INSERT INTO api_keys (
                user_id, key_hash, key_prefix, name, scopes,
                rate_limit_per_hour, expires_at
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7)
            RETURNING *
            "#,
        )
        .bind(params.user_id)
        .bind(&params.key_hash)
        .bind(&params.key_prefix)
        .bind(&params.name)
        .bind(&scopes_json)
        .bind(params.rate_limit_per_hour)
        .bind(params.expires_at)
        .fetch_one(&self.pool)
        .await?;

        Ok(api_key)
    }

    /// Find API key by hash
    pub async fn find_by_hash(&self, key_hash: &str) -> Result<Option<ApiKey>> {
        let api_key = sqlx::query_as::<_, ApiKey>(
            r#"
            SELECT * FROM api_keys
            WHERE key_hash = $1
            "#,
        )
        .bind(key_hash)
        .fetch_optional(&self.pool)
        .await?;

        Ok(api_key)
    }

    /// Find API key by ID
    pub async fn find_by_id(&self, id: Uuid) -> Result<Option<ApiKey>> {
        let api_key = sqlx::query_as::<_, ApiKey>(
            r#"
            SELECT * FROM api_keys
            WHERE id = $1
            "#,
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await?;

        Ok(api_key)
    }

    /// Get active API keys for a user
    pub async fn get_active_keys(&self, user_id: Uuid) -> Result<Vec<ApiKeySummary>> {
        let keys = sqlx::query_as::<_, ApiKey>(
            r#"
            SELECT * FROM api_keys
            WHERE user_id = $1
              AND revoked_at IS NULL
              AND (expires_at IS NULL OR expires_at > NOW())
            ORDER BY created_at DESC
            "#,
        )
        .bind(user_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(keys.into_iter().map(Self::to_summary).collect())
    }

    /// Get all API keys for a user (including revoked/expired)
    pub async fn get_user_keys(&self, user_id: Uuid) -> Result<Vec<ApiKeySummary>> {
        let keys = sqlx::query_as::<_, ApiKey>(
            r#"
            SELECT * FROM api_keys
            WHERE user_id = $1
            ORDER BY created_at DESC
            "#,
        )
        .bind(user_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(keys.into_iter().map(Self::to_summary).collect())
    }

    /// Update last used timestamp
    pub async fn update_last_used(&self, id: Uuid) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE api_keys
            SET last_used_at = NOW()
            WHERE id = $1
            "#,
        )
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Revoke an API key
    pub async fn revoke(&self, id: Uuid) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE api_keys
            SET revoked_at = NOW()
            WHERE id = $1
            "#,
        )
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Delete an API key (permanent)
    pub async fn delete(&self, id: Uuid) -> Result<()> {
        sqlx::query(
            r#"
            DELETE FROM api_keys
            WHERE id = $1
            "#,
        )
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Update API key name
    pub async fn update_name(&self, id: Uuid, name: &str) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE api_keys
            SET name = $1
            WHERE id = $2
            "#,
        )
        .bind(name)
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Update API key scopes
    pub async fn update_scopes(&self, id: Uuid, scopes: Vec<String>) -> Result<()> {
        let scopes_json = serde_json::to_value(&scopes)
            .map_err(|e| DbError::Validation(format!("Invalid scopes: {}", e)))?;

        sqlx::query(
            r#"
            UPDATE api_keys
            SET scopes = $1
            WHERE id = $2
            "#,
        )
        .bind(&scopes_json)
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Update rate limit
    pub async fn update_rate_limit(&self, id: Uuid, rate_limit: Option<i32>) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE api_keys
            SET rate_limit_per_hour = $1
            WHERE id = $2
            "#,
        )
        .bind(rate_limit)
        .bind(id)
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Check if API key is valid (not revoked, not expired, exists)
    pub async fn is_valid(&self, key_hash: &str) -> Result<bool> {
        let result = sqlx::query_scalar::<_, bool>(
            r#"
            SELECT EXISTS (
                SELECT 1 FROM api_keys
                WHERE key_hash = $1
                  AND revoked_at IS NULL
                  AND (expires_at IS NULL OR expires_at > NOW())
            )
            "#,
        )
        .bind(key_hash)
        .fetch_one(&self.pool)
        .await?;

        Ok(result)
    }

    /// Get count of active keys for a user
    pub async fn count_active_keys(&self, user_id: Uuid) -> Result<i64> {
        let count = sqlx::query_scalar::<_, i64>(
            r#"
            SELECT COUNT(*)
            FROM api_keys
            WHERE user_id = $1
              AND revoked_at IS NULL
              AND (expires_at IS NULL OR expires_at > NOW())
            "#,
        )
        .bind(user_id)
        .fetch_one(&self.pool)
        .await?;

        Ok(count)
    }

    /// Clean up expired keys (soft delete by marking as revoked)
    pub async fn cleanup_expired(&self) -> Result<u64> {
        let result = sqlx::query(
            r#"
            UPDATE api_keys
            SET revoked_at = NOW()
            WHERE expires_at IS NOT NULL
              AND expires_at <= NOW()
              AND revoked_at IS NULL
            "#,
        )
        .execute(&self.pool)
        .await?;

        Ok(result.rows_affected())
    }

    /// Verify key has required scope
    pub async fn has_scope(&self, id: Uuid, required_scope: &str) -> Result<bool> {
        let api_key = self
            .find_by_id(id)
            .await?
            .ok_or_else(|| DbError::NotFound("API key not found".to_string()))?;

        let scopes: Vec<String> = serde_json::from_value(api_key.scopes)
            .map_err(|e| DbError::Validation(format!("Invalid scopes format: {}", e)))?;

        Ok(scopes.contains(&required_scope.to_string()) || scopes.contains(&"*".to_string()))
    }

    /// Convert ApiKey to ApiKeySummary
    fn to_summary(key: ApiKey) -> ApiKeySummary {
        let scopes: Vec<String> = serde_json::from_value(key.scopes.clone()).unwrap_or_default();
        let is_active = key.revoked_at.is_none()
            && (key.expires_at.is_none() || key.expires_at.unwrap() > Utc::now());

        ApiKeySummary {
            id: key.id,
            key_prefix: key.key_prefix,
            name: key.name,
            scopes,
            rate_limit_per_hour: key.rate_limit_per_hour,
            last_used_at: key.last_used_at,
            expires_at: key.expires_at,
            is_active,
            created_at: key.created_at,
        }
    }
}

/// Execute API key operations within a transaction
pub async fn execute_in_transaction<'a, E, F, T>(executor: E, f: F) -> Result<T>
where
    E: Executor<'a, Database = Postgres>,
    F: FnOnce(E) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<T>> + Send + 'a>>,
{
    f(executor).await
}

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

    #[test]
    fn test_create_api_key_params() {
        let params = CreateApiKey {
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Test API Key".to_string(),
            scopes: vec!["tokens:read".to_string(), "orders:write".to_string()],
            rate_limit_per_hour: Some(1000),
            expires_at: None,
        };

        assert_eq!(params.name, "Test API Key");
        assert_eq!(params.scopes.len(), 2);
    }

    #[test]
    fn test_api_key_summary_creation() {
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Test Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: None,
            expires_at: None,
            revoked_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let summary = ApiKeyRepository::to_summary(key.clone());
        assert_eq!(summary.id, key.id);
        assert_eq!(summary.key_prefix, key.key_prefix);
        assert!(summary.is_active);
    }

    #[test]
    fn test_expired_key_is_inactive() {
        let expired_at = Utc::now() - Duration::hours(1);
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Expired Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: None,
            expires_at: Some(expired_at),
            revoked_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let summary = ApiKeyRepository::to_summary(key);
        assert!(!summary.is_active);
    }

    #[test]
    fn test_revoked_key_is_inactive() {
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Revoked Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: None,
            expires_at: None,
            revoked_at: Some(Utc::now()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let summary = ApiKeyRepository::to_summary(key);
        assert!(!summary.is_active);
    }

    #[test]
    fn test_scopes_serialization() {
        let scopes = vec!["tokens:read".to_string(), "orders:write".to_string()];
        let json = serde_json::to_value(&scopes).unwrap();
        let deserialized: Vec<String> = serde_json::from_value(json).unwrap();
        assert_eq!(scopes, deserialized);
    }

    #[test]
    fn test_wildcard_scope() {
        let scopes = ["*".to_string()];
        assert!(scopes.contains(&"*".to_string()));
    }

    #[test]
    fn test_multiple_scopes_validation() {
        let scopes = [
            "tokens:read".to_string(),
            "tokens:write".to_string(),
            "orders:read".to_string(),
            "orders:write".to_string(),
            "trades:read".to_string(),
        ];
        assert_eq!(scopes.len(), 5);
        assert!(scopes.contains(&"tokens:read".to_string()));
        assert!(scopes.contains(&"trades:read".to_string()));
    }

    #[test]
    fn test_key_with_no_expiration() {
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Permanent Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: None,
            expires_at: None,
            revoked_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let summary = ApiKeyRepository::to_summary(key.clone());
        assert!(summary.is_active);
        assert!(summary.expires_at.is_none());
    }

    #[test]
    fn test_key_with_future_expiration() {
        let future_expiration = Utc::now() + Duration::days(30);
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Future Expiry Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: None,
            expires_at: Some(future_expiration),
            revoked_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        let summary = ApiKeyRepository::to_summary(key);
        assert!(summary.is_active);
    }

    #[test]
    fn test_key_with_custom_rate_limit() {
        let key = CreateApiKey {
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "High Rate Limit Key".to_string(),
            scopes: vec!["tokens:read".to_string()],
            rate_limit_per_hour: Some(100000),
            expires_at: None,
        };

        assert_eq!(key.rate_limit_per_hour, Some(100000));
    }

    #[test]
    fn test_key_with_no_rate_limit() {
        let key = CreateApiKey {
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Unlimited Key".to_string(),
            scopes: vec!["*".to_string()],
            rate_limit_per_hour: None,
            expires_at: None,
        };

        assert!(key.rate_limit_per_hour.is_none());
    }

    #[test]
    fn test_empty_scopes() {
        let scopes: Vec<String> = vec![];
        let json = serde_json::to_value(&scopes).unwrap();
        let deserialized: Vec<String> = serde_json::from_value(json).unwrap();
        assert_eq!(scopes, deserialized);
        assert!(deserialized.is_empty());
    }

    #[test]
    fn test_key_prefix_format() {
        let key = CreateApiKey {
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_test123".to_string(),
            name: "Test Key".to_string(),
            scopes: vec!["tokens:read".to_string()],
            rate_limit_per_hour: Some(1000),
            expires_at: None,
        };

        assert!(key.key_prefix.starts_with("kaccy_"));
        assert!(key.key_prefix.len() >= 8);
    }

    #[test]
    fn test_last_used_tracking() {
        let now = Utc::now();
        let key = ApiKey {
            id: Uuid::new_v4(),
            user_id: Uuid::new_v4(),
            key_hash: "hash123".to_string(),
            key_prefix: "kaccy_12".to_string(),
            name: "Used Key".to_string(),
            scopes: serde_json::json!(["tokens:read"]),
            rate_limit_per_hour: Some(1000),
            last_used_at: Some(now),
            expires_at: None,
            revoked_at: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        assert!(key.last_used_at.is_some());
        assert_eq!(key.last_used_at.unwrap(), now);
    }
}