blueprint-auth 0.2.0-alpha.3

Blueprint HTTP/WS Authentication
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
//! Long-lived API key management
//!
//! API keys are the primary authentication mechanism for services.
//! They follow the format `ak_<key_id>.<secret>` where:
//!
//! - `ak_` is a fixed prefix for identification
//! - `key_id` is a unique identifier (5 chars, base64url)
//! - `secret` is the secret part (32 bytes, base64url encoded)
//!
//! # Storage
//!
//! Keys are stored in RocksDB with:
//! - The full key is never stored, only a hash
//! - Key metadata includes service ID, creation time, etc.
//! - Supports expiration and enabled/disabled states
//!
//! # Usage
//!
//! API keys are exchanged for short-lived access tokens:
//!
//! ```text
//! // Client sends API key
//! Authorization: Bearer ak_2n4f8.w9x7y6z5a4b3c2d1
//!
//! // Server validates and returns access token
//! {
//!   "access_token": "v4.local.xxxxx",
//!   "expires_in": 900
//! }
//! ```

use base64::Engine;
use blueprint_std::rand::{CryptoRng, RngCore};
use prost::Message;
use std::collections::BTreeMap;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::{
    Error,
    api_tokens::CUSTOM_ENGINE,
    db::{RocksDb, cf},
    types::ServiceId,
};

/// Long-lived API Key model stored in database
#[derive(prost::Message, Clone)]
pub struct ApiKeyModel {
    /// Unique database ID
    #[prost(uint64)]
    pub id: u64,
    /// API key identifier (e.g., "ak_2n4f8...")
    #[prost(string)]
    pub key_id: String,
    /// Hashed secret part of the API key
    #[prost(string)]
    pub key_hash: String,
    /// Service ID this key belongs to
    #[prost(uint64)]
    pub service_id: u64,
    /// Sub-service ID (zero means no sub-service)
    #[prost(uint64)]
    pub sub_service_id: u64,
    /// When this key was created (seconds since epoch)
    #[prost(uint64)]
    pub created_at: u64,
    /// When this key was last used (seconds since epoch)
    #[prost(uint64)]
    pub last_used: u64,
    /// When this key expires (seconds since epoch)
    #[prost(uint64)]
    pub expires_at: u64,
    /// Whether this key is enabled
    #[prost(bool)]
    pub is_enabled: bool,
    /// Default headers to include in access tokens (JSON-encoded)
    #[prost(bytes)]
    pub default_headers: Vec<u8>,
    /// Human-readable description
    #[prost(string)]
    pub description: String,
}

/// Generated API Key containing both public and secret parts
#[derive(Debug, Clone)]
pub struct GeneratedApiKey {
    /// Public key identifier
    pub key_id: String,
    /// Full API key (key_id + secret)
    pub full_key: String,
    /// Service ID this key is for
    pub service_id: ServiceId,
    /// Expiration timestamp
    pub expires_at: u64,
    /// Default headers
    pub default_headers: BTreeMap<String, String>,
}

/// API Key generator
pub struct ApiKeyGenerator {
    prefix: String,
}

impl Default for ApiKeyGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl ApiKeyGenerator {
    /// Create new generator with default prefix "ak_"
    pub fn new() -> Self {
        Self {
            prefix: "ak_".to_string(),
        }
    }

    /// Create generator with custom prefix
    pub fn with_prefix(prefix: &str) -> Self {
        Self {
            prefix: prefix.to_string(),
        }
    }

    /// Generate a new API key
    pub fn generate_key<R: RngCore + CryptoRng>(
        &self,
        service_id: ServiceId,
        expires_at: u64,
        default_headers: BTreeMap<String, String>,
        rng: &mut R,
    ) -> GeneratedApiKey {
        // Generate 32 bytes of randomness
        let mut secret_bytes = vec![0u8; 32];
        rng.fill_bytes(&mut secret_bytes);

        // Create key identifier (first 8 bytes, base64 encoded)
        let key_id = format!(
            "{}{}",
            self.prefix,
            CUSTOM_ENGINE.encode(&secret_bytes[..8])
        );

        // Full key is key_id + "." + remaining 24 bytes base64 encoded
        let secret_part = CUSTOM_ENGINE.encode(&secret_bytes[8..]);
        let full_key = format!("{key_id}.{secret_part}");

        GeneratedApiKey {
            key_id,
            full_key,
            service_id,
            expires_at,
            default_headers,
        }
    }
}

impl GeneratedApiKey {
    /// Get the public key identifier
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Get the full API key (to be shared with client)
    pub fn full_key(&self) -> &str {
        &self.full_key
    }

    /// Get expiration time
    pub fn expires_at(&self) -> u64 {
        self.expires_at
    }

    /// Get default headers
    pub fn default_headers(&self) -> &BTreeMap<String, String> {
        &self.default_headers
    }
}

impl ApiKeyModel {
    /// Find API key by key_id
    pub fn find_by_key_id(key_id: &str, db: &RocksDb) -> Result<Option<Self>, Error> {
        let cf = db
            .cf_handle(cf::API_KEYS_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_CF))?;

        if let Some(key_bytes) = db.get_pinned_cf(&cf, key_id.as_bytes())? {
            let model = Self::decode(key_bytes.as_ref())?;
            Ok(Some(model))
        } else {
            Ok(None)
        }
    }

    /// Find API key by database ID
    pub fn find_by_id(id: u64, db: &RocksDb) -> Result<Option<Self>, Error> {
        let cf = db
            .cf_handle(cf::API_KEYS_BY_ID_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_BY_ID_CF))?;

        if let Some(key_id_bytes) = db.get_pinned_cf(&cf, id.to_be_bytes())? {
            let key_id =
                String::from_utf8(key_id_bytes.to_vec()).map_err(|_| Error::UnknownKeyType)?; // Reusing error type
            Self::find_by_key_id(&key_id, db)
        } else {
            Ok(None)
        }
    }

    /// Validate if the given full key matches this stored key
    pub fn validates_key(&self, full_key: &str) -> bool {
        // Parse full key: "ak_xxxx.yyyy"
        if let Some((key_id_part, _)) = full_key.split_once('.') {
            if key_id_part != self.key_id {
                return false;
            }

            // Hash the full key and compare
            use tiny_keccak::Hasher;
            let mut hasher = tiny_keccak::Keccak::v256();
            hasher.update(full_key.as_bytes());
            let mut output = [0u8; 32];
            hasher.finalize(&mut output);
            let computed_hash = CUSTOM_ENGINE.encode(output);

            use subtle::ConstantTimeEq;
            self.key_hash
                .as_bytes()
                .ct_eq(computed_hash.as_bytes())
                .into()
        } else {
            false
        }
    }

    /// Check if key is expired
    pub fn is_expired(&self) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now >= self.expires_at
    }

    /// Update last used timestamp
    pub fn update_last_used(&mut self, db: &RocksDb) -> Result<(), Error> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self.last_used = now;
        self.save(db)
    }

    /// Get default headers as BTreeMap
    pub fn get_default_headers(&self) -> BTreeMap<String, String> {
        if self.default_headers.is_empty() {
            BTreeMap::new()
        } else {
            serde_json::from_slice(&self.default_headers).unwrap_or_default()
        }
    }

    /// Set default headers from BTreeMap
    pub fn set_default_headers(&mut self, headers: &BTreeMap<String, String>) {
        self.default_headers = serde_json::to_vec(headers).unwrap_or_default();
    }

    /// Get service ID
    pub fn service_id(&self) -> ServiceId {
        ServiceId::new(self.service_id).with_subservice(self.sub_service_id)
    }

    /// Save to database
    pub fn save(&mut self, db: &RocksDb) -> Result<(), Error> {
        let keys_cf = db
            .cf_handle(cf::API_KEYS_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_CF))?;
        let ids_cf = db
            .cf_handle(cf::API_KEYS_BY_ID_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_BY_ID_CF))?;

        if self.id == 0 {
            self.create(db)
        } else {
            // Update existing
            let key_bytes = self.encode_to_vec();
            db.put_cf(&keys_cf, self.key_id.as_bytes(), key_bytes)?;
            db.put_cf(&ids_cf, self.id.to_be_bytes(), self.key_id.as_bytes())?;
            Ok(())
        }
    }

    fn create(&mut self, db: &RocksDb) -> Result<(), Error> {
        let keys_cf = db
            .cf_handle(cf::API_KEYS_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_CF))?;
        let ids_cf = db
            .cf_handle(cf::API_KEYS_BY_ID_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_BY_ID_CF))?;
        let seq_cf = db
            .cf_handle(cf::SEQ_CF)
            .ok_or(Error::UnknownColumnFamily(cf::SEQ_CF))?;

        let txn = db.transaction();

        // Increment sequence
        let mut retry_count = 0;
        let max_retries = 10;
        loop {
            let result = txn.merge_cf(&seq_cf, b"api_keys", 1u64.to_be_bytes());
            match result {
                Ok(()) => break,
                Err(e)
                    if matches!(
                        e.kind(),
                        rocksdb::ErrorKind::Busy | rocksdb::ErrorKind::TryAgain
                    ) =>
                {
                    retry_count += 1;
                    if retry_count >= max_retries {
                        return Err(Error::RocksDB(e));
                    }
                }
                Err(e) => return Err(Error::RocksDB(e)),
            }
        }

        let next_id = txn
            .get_cf(&seq_cf, b"api_keys")?
            .map(|v| {
                let mut id = [0u8; 8];
                id.copy_from_slice(&v);
                u64::from_be_bytes(id)
            })
            .unwrap_or(1u64);

        self.id = next_id;
        let key_bytes = self.encode_to_vec();
        txn.put_cf(&keys_cf, self.key_id.as_bytes(), key_bytes)?;
        txn.put_cf(&ids_cf, next_id.to_be_bytes(), self.key_id.as_bytes())?;

        txn.commit()?;
        Ok(())
    }

    /// Delete from database
    pub fn delete(&self, db: &RocksDb) -> Result<(), Error> {
        let keys_cf = db
            .cf_handle(cf::API_KEYS_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_CF))?;
        let ids_cf = db
            .cf_handle(cf::API_KEYS_BY_ID_CF)
            .ok_or(Error::UnknownColumnFamily(cf::API_KEYS_BY_ID_CF))?;

        let txn = db.transaction();
        txn.delete_cf(&keys_cf, self.key_id.as_bytes())?;
        txn.delete_cf(&ids_cf, self.id.to_be_bytes())?;
        txn.commit()?;
        Ok(())
    }
}

impl From<&GeneratedApiKey> for ApiKeyModel {
    fn from(key: &GeneratedApiKey) -> Self {
        use tiny_keccak::Hasher;

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Hash the full key
        let mut hasher = tiny_keccak::Keccak::v256();
        hasher.update(key.full_key.as_bytes());
        let mut output = [0u8; 32];
        hasher.finalize(&mut output);
        let key_hash = CUSTOM_ENGINE.encode(output);

        let mut model = Self {
            id: 0,
            key_id: key.key_id.clone(),
            key_hash,
            service_id: key.service_id.0,
            sub_service_id: key.service_id.1,
            created_at: now,
            last_used: 0,
            expires_at: key.expires_at,
            is_enabled: true,
            default_headers: Vec::new(),
            description: String::new(),
        };

        model.set_default_headers(&key.default_headers);
        model
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ServiceId;
    use tempfile::tempdir;

    #[test]
    fn test_api_key_generation() {
        let mut rng = blueprint_std::BlueprintRng::new();
        let generator = ApiKeyGenerator::new();
        let service_id = ServiceId::new(1);
        let expires_at = 1234567890;
        let mut headers = BTreeMap::new();
        headers.insert("X-Tenant-Id".to_string(), "tenant123".to_string());

        let key = generator.generate_key(service_id, expires_at, headers.clone(), &mut rng);

        assert!(key.key_id().starts_with("ak_"));
        assert!(key.full_key().contains('.'));
        assert_eq!(key.expires_at(), expires_at);
        assert_eq!(key.default_headers(), &headers);

        // Should have format: ak_xxxx.yyyy
        let parts: Vec<&str> = key.full_key().split('.').collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], key.key_id());
    }

    #[test]
    fn test_api_key_validation() {
        let mut rng = blueprint_std::BlueprintRng::new();
        let generator = ApiKeyGenerator::new();

        let key = generator.generate_key(ServiceId::new(1), 1234567890, BTreeMap::new(), &mut rng);

        let model = ApiKeyModel::from(&key);

        // Should validate correct key
        assert!(model.validates_key(key.full_key()));

        // Should not validate incorrect key
        let wrong_key = key.full_key().replace('a', "b");
        assert!(!model.validates_key(&wrong_key));

        // Should not validate malformed key
        assert!(!model.validates_key("invalid"));
        assert!(!model.validates_key("ak_test"));
    }

    #[test]
    fn test_api_key_database_operations() {
        let tmp_dir = tempdir().unwrap();
        let db_config = crate::db::RocksDbConfig::default();
        let db = RocksDb::open(tmp_dir.path(), &db_config).unwrap();
        let mut rng = blueprint_std::BlueprintRng::new();
        let generator = ApiKeyGenerator::new();

        let key = generator.generate_key(ServiceId::new(1), 1234567890, BTreeMap::new(), &mut rng);

        let mut model = ApiKeyModel::from(&key);

        // Save should assign ID
        model.save(&db).unwrap();
        assert_ne!(model.id, 0);

        // Should be able to find by key_id
        let found = ApiKeyModel::find_by_key_id(key.key_id(), &db)
            .unwrap()
            .unwrap();
        assert_eq!(found.key_id, model.key_id);
        assert_eq!(found.id, model.id);

        // Should be able to find by ID
        let found_by_id = ApiKeyModel::find_by_id(model.id, &db).unwrap().unwrap();
        assert_eq!(found_by_id.key_id, model.key_id);

        // Should validate the key
        assert!(found.validates_key(key.full_key()));

        // Delete should work
        model.delete(&db).unwrap();
        assert!(
            ApiKeyModel::find_by_key_id(key.key_id(), &db)
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn test_expiration() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut model = ApiKeyModel {
            id: 1,
            key_id: "ak_test".to_string(),
            key_hash: "hash".to_string(),
            service_id: 1,
            sub_service_id: 0,
            created_at: now,
            last_used: 0,
            expires_at: now - 1, // Expired
            is_enabled: true,
            default_headers: Vec::new(),
            description: "Test".to_string(),
        };

        assert!(model.is_expired());

        model.expires_at = now + 3600; // Not expired
        assert!(!model.is_expired());
    }

    #[test]
    fn test_headers_serialization() {
        let mut model = ApiKeyModel {
            id: 1,
            key_id: "ak_test".to_string(),
            key_hash: "hash".to_string(),
            service_id: 1,
            sub_service_id: 0,
            created_at: 0,
            last_used: 0,
            expires_at: 0,
            is_enabled: true,
            default_headers: Vec::new(),
            description: "Test".to_string(),
        };

        let mut headers = BTreeMap::new();
        headers.insert("X-Test".to_string(), "value".to_string());

        model.set_default_headers(&headers);
        let retrieved = model.get_default_headers();

        assert_eq!(retrieved, headers);
    }
}