engram-core 0.21.1

AI Memory Infrastructure - Persistent memory for AI agents with semantic search
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
//! API key and token management

use crate::auth::{PermissionSet, UserId};
use crate::error::{EngramError, Result};
use chrono::{DateTime, Utc};
use rand::Rng;
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;

/// API key with prefix for easy identification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKey {
    pub id: String,
    pub user_id: UserId,
    pub name: String,
    pub key_prefix: String,
    pub permissions: PermissionSet,
    pub namespace: Option<String>,
    pub expires_at: Option<DateTime<Utc>>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub is_active: bool,
    pub created_at: DateTime<Utc>,
}

/// Token claims for validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenClaims {
    pub user_id: UserId,
    pub key_id: String,
    pub permissions: PermissionSet,
    pub namespace: Option<String>,
    pub issued_at: DateTime<Utc>,
    pub expires_at: Option<DateTime<Utc>>,
}

impl TokenClaims {
    /// Check if the token is expired
    pub fn is_expired(&self) -> bool {
        if let Some(exp) = self.expires_at {
            return Utc::now() > exp;
        }
        false
    }
}

/// API key manager
pub struct ApiKeyManager<'a> {
    conn: &'a Connection,
}

impl<'a> ApiKeyManager<'a> {
    /// Create a new API key manager
    pub fn new(conn: &'a Connection) -> Self {
        Self { conn }
    }

    /// Generate a new API key
    /// Returns (ApiKey, raw_key) - raw_key should only be shown once
    pub fn create_api_key(
        &self,
        user_id: &UserId,
        name: &str,
        permissions: PermissionSet,
        namespace: Option<String>,
        expires_in_days: Option<i64>,
    ) -> Result<(ApiKey, String)> {
        let id = Uuid::new_v4().to_string();
        let raw_key = generate_api_key();
        let (key_salt, key_hash) = hash_key(&raw_key);
        let key_prefix = &raw_key[..12]; // Show first 12 chars for identification

        let expires_at = expires_in_days.map(|days| Utc::now() + chrono::Duration::days(days));

        let permissions_json = serde_json::to_string(&permissions)?;

        self.conn.execute(
            r#"
            INSERT INTO api_keys (id, user_id, key_hash, key_salt, key_prefix, name, permissions, namespace, expires_at, is_active, created_at)
            VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, datetime('now'))
            "#,
            params![
                id,
                user_id.as_str(),
                key_hash,
                key_salt,
                key_prefix,
                name,
                permissions_json,
                namespace,
                expires_at.map(|dt| dt.to_rfc3339()),
            ],
        )?;

        let api_key = ApiKey {
            id,
            user_id: user_id.clone(),
            name: name.to_string(),
            key_prefix: key_prefix.to_string(),
            permissions,
            namespace,
            expires_at,
            last_used_at: None,
            is_active: true,
            created_at: Utc::now(),
        };

        Ok((api_key, raw_key))
    }

    /// Validate an API key and return claims
    pub fn validate_key(&self, raw_key: &str) -> Result<Option<TokenClaims>> {
        // Use the key prefix to narrow the DB search, then verify the hash in-process.
        if raw_key.len() < 12 {
            return Ok(None);
        }
        let key_prefix = &raw_key[..12];

        let mut stmt = self.conn.prepare(
            r#"
            SELECT ak.id, ak.user_id, ak.permissions, ak.namespace, ak.expires_at,
                   u.is_active as user_active, ak.key_hash, ak.key_salt
            FROM api_keys ak
            JOIN users u ON ak.user_id = u.id
            WHERE ak.key_prefix = ?1 AND ak.is_active = 1
            "#,
        )?;

        type Row = (
            String,
            String,
            String,
            Option<String>,
            Option<String>,
            bool,
            String,
            String,
        );
        let rows: Vec<Row> = stmt
            .query_map(params![key_prefix], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get(5)?,
                    row.get(6)?,
                    row.get(7)?,
                ))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        let result = rows
            .into_iter()
            .find(|(_, _, _, _, _, _, stored_hash, salt)| {
                hash_key_with_salt(raw_key, salt) == *stored_hash
            });

        if let Some((
            key_id,
            user_id,
            permissions_json,
            namespace,
            expires_at_str,
            user_active,
            _,
            _,
        )) = result
        {
            if !user_active {
                return Ok(None);
            }

            let expires_at = expires_at_str
                .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                .map(|dt| dt.with_timezone(&Utc));

            // Check expiration
            if let Some(exp) = expires_at {
                if Utc::now() > exp {
                    return Ok(None);
                }
            }

            // Update last used
            self.conn.execute(
                "UPDATE api_keys SET last_used_at = datetime('now') WHERE id = ?1",
                params![key_id],
            )?;

            let permissions: PermissionSet = serde_json::from_str(&permissions_json)?;

            Ok(Some(TokenClaims {
                user_id: UserId::from_string(user_id),
                key_id,
                permissions,
                namespace,
                issued_at: Utc::now(),
                expires_at,
            }))
        } else {
            Ok(None)
        }
    }

    /// Get API key by ID (without the raw key)
    pub fn get_key(&self, id: &str) -> Result<Option<ApiKey>> {
        self.conn
            .query_row(
                r#"
                SELECT id, user_id, key_prefix, name, permissions, namespace, expires_at, last_used_at, is_active, created_at
                FROM api_keys WHERE id = ?1
                "#,
                params![id],
                |row| {
                    let permissions_json: String = row.get(4)?;
                    Ok(ApiKey {
                        id: row.get(0)?,
                        user_id: UserId::from_string(row.get::<_, String>(1)?),
                        key_prefix: row.get(2)?,
                        name: row.get(3)?,
                        permissions: serde_json::from_str(&permissions_json).unwrap_or_default(),
                        namespace: row.get(5)?,
                        expires_at: row.get::<_, Option<String>>(6)?
                            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                            .map(|dt| dt.with_timezone(&Utc)),
                        last_used_at: row.get::<_, Option<String>>(7)?
                            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                            .map(|dt| dt.with_timezone(&Utc)),
                        is_active: row.get(8)?,
                        created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(9)?)
                            .map(|dt| dt.with_timezone(&Utc))
                            .unwrap_or_else(|_| Utc::now()),
                    })
                },
            )
            .optional()
            .map_err(EngramError::from)
    }

    /// List API keys for a user
    pub fn list_keys(&self, user_id: &UserId) -> Result<Vec<ApiKey>> {
        let mut stmt = self.conn.prepare(
            r#"
            SELECT id, user_id, key_prefix, name, permissions, namespace, expires_at, last_used_at, is_active, created_at
            FROM api_keys WHERE user_id = ?1 ORDER BY created_at DESC
            "#,
        )?;

        let keys = stmt
            .query_map(params![user_id.as_str()], |row| {
                let permissions_json: String = row.get(4)?;
                Ok(ApiKey {
                    id: row.get(0)?,
                    user_id: UserId::from_string(row.get::<_, String>(1)?),
                    key_prefix: row.get(2)?,
                    name: row.get(3)?,
                    permissions: serde_json::from_str(&permissions_json).unwrap_or_default(),
                    namespace: row.get(5)?,
                    expires_at: row
                        .get::<_, Option<String>>(6)?
                        .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                        .map(|dt| dt.with_timezone(&Utc)),
                    last_used_at: row
                        .get::<_, Option<String>>(7)?
                        .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
                        .map(|dt| dt.with_timezone(&Utc)),
                    is_active: row.get(8)?,
                    created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(9)?)
                        .map(|dt| dt.with_timezone(&Utc))
                        .unwrap_or_else(|_| Utc::now()),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(keys)
    }

    /// Revoke an API key
    pub fn revoke_key(&self, id: &str) -> Result<bool> {
        let updated = self.conn.execute(
            "UPDATE api_keys SET is_active = 0 WHERE id = ?1",
            params![id],
        )?;
        Ok(updated > 0)
    }

    /// Delete an API key
    pub fn delete_key(&self, id: &str) -> Result<bool> {
        let deleted = self
            .conn
            .execute("DELETE FROM api_keys WHERE id = ?1", params![id])?;
        Ok(deleted > 0)
    }
}

/// Generate a secure API key
fn generate_api_key() -> String {
    let mut rng = rand::thread_rng();
    let bytes: Vec<u8> = (0..32).map(|_| rng.gen()).collect();
    format!("eng_{}", hex::encode(bytes))
}

/// Generate a random 16-byte salt and return `(salt_hex, hash_hex)`.
///
/// The salt is unique per call, so two invocations with the same key produce
/// different hashes. This defends against rainbow-table attacks: an attacker
/// who obtains the hash database cannot precompute a lookup table without
/// knowing each row's individual salt.
///
/// The hash is computed as SHA-256(salt_bytes || key_bytes).
fn hash_key(key: &str) -> (String, String) {
    let mut rng = rand::thread_rng();
    let salt_bytes: Vec<u8> = (0..16).map(|_| rng.gen()).collect();
    let salt_hex = hex::encode(&salt_bytes);
    let hash = hash_key_with_salt(key, &salt_hex);
    (salt_hex, hash)
}

/// Recompute the hash for a key given an existing salt (hex-encoded).
fn hash_key_with_salt(key: &str, salt_hex: &str) -> String {
    let salt_bytes = hex::decode(salt_hex).unwrap_or_default();
    let mut hasher = Sha256::new();
    hasher.update(&salt_bytes);
    hasher.update(key.as_bytes());
    hex::encode(hasher.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{init_auth_tables, Permission, ResourceType, User, UserManager};

    fn setup_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        init_auth_tables(&conn).unwrap();
        conn
    }

    #[test]
    fn test_create_and_validate_api_key() {
        let conn = setup_db();

        // Create user first
        let user = User::new("testuser");
        UserManager::new(&conn).create_user(&user, None).unwrap();

        // Create API key
        let manager = ApiKeyManager::new(&conn);
        let (api_key, raw_key) = manager
            .create_api_key(
                &user.id,
                "Test Key",
                PermissionSet::standard_user(),
                None,
                None,
            )
            .unwrap();

        assert!(raw_key.starts_with("eng_"));
        assert_eq!(api_key.name, "Test Key");

        // Validate key
        let claims = manager.validate_key(&raw_key).unwrap().unwrap();
        assert_eq!(claims.user_id, user.id);
        assert!(claims
            .permissions
            .has_permission(Permission::Read, ResourceType::Memory));
    }

    #[test]
    fn test_validate_invalid_key() {
        let conn = setup_db();
        let manager = ApiKeyManager::new(&conn);

        let claims = manager.validate_key("eng_invalid_key_here").unwrap();
        assert!(claims.is_none());
    }

    #[test]
    fn test_revoke_key() {
        let conn = setup_db();

        let user = User::new("testuser");
        UserManager::new(&conn).create_user(&user, None).unwrap();

        let manager = ApiKeyManager::new(&conn);
        let (api_key, raw_key) = manager
            .create_api_key(
                &user.id,
                "Revoke Test",
                PermissionSet::read_only(),
                None,
                None,
            )
            .unwrap();

        // Key should work
        assert!(manager.validate_key(&raw_key).unwrap().is_some());

        // Revoke key
        manager.revoke_key(&api_key.id).unwrap();

        // Key should no longer work
        assert!(manager.validate_key(&raw_key).unwrap().is_none());
    }

    #[test]
    fn test_expired_key() {
        let conn = setup_db();

        let user = User::new("testuser");
        UserManager::new(&conn).create_user(&user, None).unwrap();

        let manager = ApiKeyManager::new(&conn);

        // Create key that expires in -1 days (already expired)
        // We'll manually set the expiration to test
        let (_api_key, raw_key) = manager
            .create_api_key(
                &user.id,
                "Expiring Key",
                PermissionSet::read_only(),
                None,
                Some(-1),
            )
            .unwrap();

        // Key should be expired
        let claims = manager.validate_key(&raw_key).unwrap();
        assert!(claims.is_none());
    }

    #[test]
    fn test_list_keys() {
        let conn = setup_db();

        let user = User::new("testuser");
        UserManager::new(&conn).create_user(&user, None).unwrap();

        let manager = ApiKeyManager::new(&conn);
        manager
            .create_api_key(&user.id, "Key 1", PermissionSet::read_only(), None, None)
            .unwrap();
        manager
            .create_api_key(
                &user.id,
                "Key 2",
                PermissionSet::standard_user(),
                None,
                None,
            )
            .unwrap();

        let keys = manager.list_keys(&user.id).unwrap();
        assert_eq!(keys.len(), 2);
    }

    #[test]
    fn test_hash_key_includes_salt_and_is_unique() {
        let (salt1, hash1) = hash_key("eng_samekey");
        let (salt2, hash2) = hash_key("eng_samekey");
        assert_ne!(salt1, salt2, "salts must be unique per call");
        assert_ne!(hash1, hash2, "hashes must differ when salts differ");
    }

    #[test]
    fn test_hash_key_verify_roundtrip() {
        let raw = "eng_testkey123";
        let (salt, hash) = hash_key(raw);
        let recomputed = hash_key_with_salt(raw, &salt);
        assert_eq!(hash, recomputed, "recompute with same salt must match");
    }

    #[test]
    fn test_hash_key_wrong_key_differs() {
        let (salt, hash) = hash_key("eng_rightkey");
        let wrong = hash_key_with_salt("eng_wrongkey", &salt);
        assert_ne!(hash, wrong, "different key with same salt must not match");
    }

    #[test]
    fn test_create_api_key_stores_salt() {
        let conn = setup_db();
        let user = User::new("saltuser");
        UserManager::new(&conn).create_user(&user, None).unwrap();

        let manager = ApiKeyManager::new(&conn);
        manager
            .create_api_key(
                &user.id,
                "Salt Test",
                PermissionSet::standard_user(),
                None,
                None,
            )
            .unwrap();

        let salt: String = conn
            .query_row("SELECT key_salt FROM api_keys LIMIT 1", [], |r| r.get(0))
            .unwrap();
        assert!(!salt.is_empty(), "key_salt must be stored");
    }
}