link-common 0.5.2-rc.2

Shared Rust implementation for KalamDB link crates
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
//! Credential storage abstraction for KalamDB clients.
//!
//! Provides a trait-based system for storing and retrieving authentication
//! credentials across different storage backends (files, environment variables,
//! secure keychains, browser localStorage, etc.).
//!
//! This abstraction allows CLI tools, WASM clients, and other applications
//! to manage credentials in a platform-appropriate way.
//!
//! # Security Model
//!
//! Credentials stores **JWT tokens only**, never user/password pairs.
//! This provides better security because:
//! - JWT tokens can expire and be revoked
//! - No plaintext passwords stored on disk
//! - Tokens can have limited scopes

use kalamdb_commons::UserId;
use serde::{Deserialize, Serialize};

use crate::error::Result;

/// Stored credentials for a KalamDB instance.
///
/// Contains a JWT token that can be persisted and reused across sessions.
/// The token is obtained by authenticating with user/password via the
/// `/v1/api/auth/login` endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Credentials {
    /// Database instance identifier (e.g., "local", "production", URL)
    pub instance: String,

    /// JWT access token for authentication
    /// Obtained from the login endpoint, expires after a configured period
    pub jwt_token: String,

    /// User associated with this token (for display purposes)
    #[serde(default)]
    pub user: Option<UserId>,

    /// Preferred human-friendly name for this account, if available.
    #[serde(default)]
    pub name: Option<String>,

    /// Email associated with this token (for display purposes)
    #[serde(default)]
    pub email: Option<String>,

    /// Token expiration time in RFC3339 format (optional, for cache invalidation)
    #[serde(default)]
    pub expires_at: Option<String>,

    /// Optional: Server URL if different from instance name
    #[serde(default)]
    pub server_url: Option<String>,

    /// Refresh token for obtaining new access tokens (longer-lived)
    #[serde(default)]
    pub refresh_token: Option<String>,

    /// Refresh token expiration time in RFC3339 format
    #[serde(default)]
    pub refresh_expires_at: Option<String>,
}

impl Credentials {
    /// Create new credentials with a JWT token
    pub fn new(instance: String, jwt_token: String) -> Self {
        Self {
            instance,
            jwt_token,
            user: None,
            name: None,
            email: None,
            expires_at: None,
            server_url: None,
            refresh_token: None,
            refresh_expires_at: None,
        }
    }

    /// Create new credentials with full details
    pub fn with_details(
        instance: String,
        jwt_token: String,
        user: impl Into<UserId>,
        expires_at: String,
        server_url: Option<String>,
    ) -> Self {
        Self {
            instance,
            jwt_token,
            user: Some(user.into()),
            name: None,
            email: None,
            expires_at: Some(expires_at),
            server_url,
            refresh_token: None,
            refresh_expires_at: None,
        }
    }

    /// Create new credentials with full details including refresh token
    pub fn with_refresh_token(
        instance: String,
        jwt_token: String,
        user: impl Into<UserId>,
        expires_at: String,
        server_url: Option<String>,
        refresh_token: Option<String>,
        refresh_expires_at: Option<String>,
    ) -> Self {
        Self {
            instance,
            jwt_token,
            user: Some(user.into()),
            name: None,
            email: None,
            expires_at: Some(expires_at),
            server_url,
            refresh_token,
            refresh_expires_at,
        }
    }

    /// Attach human-friendly identity metadata.
    pub fn with_identity_metadata(mut self, name: Option<String>, email: Option<String>) -> Self {
        self.name = name.and_then(|value| {
            let trimmed = value.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        });
        self.email = email.and_then(|value| {
            let trimmed = value.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        });
        self
    }

    /// Preferred display label for this identity.
    pub fn display_label(&self) -> Option<&str> {
        self.name
            .as_deref()
            .or(self.email.as_deref())
            .or_else(|| self.user.as_ref().map(UserId::as_str))
    }

    /// Get the server URL, defaulting to instance name if not set
    pub fn get_server_url(&self) -> &str {
        self.server_url.as_deref().unwrap_or(&self.instance)
    }

    /// Check if the access token has expired (if expiration is known)
    /// Returns false if expiration is unknown (assume valid)
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = &self.expires_at {
            if let Ok(exp_ms) = crate::timestamp::parse_iso8601(expires_at) {
                return exp_ms < crate::timestamp::now();
            }
        }
        false
    }

    /// Check if the refresh token has expired (if expiration is known)
    /// Returns true if no refresh token is available or if it has expired
    pub fn is_refresh_expired(&self) -> bool {
        match (&self.refresh_token, &self.refresh_expires_at) {
            (Some(_), Some(expires_at)) => {
                if let Ok(exp_ms) = crate::timestamp::parse_iso8601(expires_at) {
                    exp_ms < crate::timestamp::now()
                } else {
                    // Invalid format, assume expired
                    true
                }
            },
            // No refresh token available
            _ => true,
        }
    }

    /// Check if we can refresh the access token
    pub fn can_refresh(&self) -> bool {
        self.refresh_token.is_some() && !self.is_refresh_expired()
    }
}

/// Trait for credential storage backends.
///
/// Implementations can store credentials in files, environment variables,
/// secure keychains, browser localStorage, or any other storage mechanism.
///
/// # Security Note
///
/// Implementations MUST ensure credentials are stored securely:
/// - Files should use restrictive permissions (0600 on Unix)
/// - Passwords should never be logged
/// - Consider encryption for sensitive deployments
///
/// # Example Implementation
///
/// ```rust,ignore
/// use kalam_client::credentials::{CredentialStore, Credentials};
///
/// struct MyCredentialStore;
///
/// impl CredentialStore for MyCredentialStore {
///     fn get_credentials(&self, instance: &str) -> Result<Option<Credentials>> {
///         // Read from your storage backend
///         Ok(None)
///     }
///     
///     fn set_credentials(&mut self, credentials: &Credentials) -> Result<()> {
///         // Write to your storage backend
///         Ok(())
///     }
///     
///     fn delete_credentials(&mut self, instance: &str) -> Result<()> {
///         // Remove from your storage backend
///         Ok(())
///     }
///     
///     fn list_instances(&self) -> Result<Vec<String>> {
///         // List all stored instances
///         Ok(vec![])
///     }
/// }
/// ```
pub trait CredentialStore {
    /// Retrieve credentials for a specific database instance
    ///
    /// Returns `Ok(None)` if no credentials are stored for the instance.
    ///
    /// # Arguments
    /// * `instance` - Instance identifier (e.g., "local", "production")
    fn get_credentials(&self, instance: &str) -> Result<Option<Credentials>>;

    /// Store credentials for a database instance
    ///
    /// Overwrites existing credentials for the same instance.
    ///
    /// # Arguments
    /// * `credentials` - Credentials to store
    fn set_credentials(&mut self, credentials: &Credentials) -> Result<()>;

    /// Delete stored credentials for an instance
    ///
    /// Returns `Ok(())` even if no credentials were stored.
    ///
    /// # Arguments
    /// * `instance` - Instance identifier to delete
    fn delete_credentials(&mut self, instance: &str) -> Result<()>;

    /// List all stored instance identifiers
    ///
    /// Returns a vector of instance names that have stored credentials.
    fn list_instances(&self) -> Result<Vec<String>>;

    /// Check if credentials exist for an instance
    ///
    /// Default implementation calls `get_credentials()` and checks for Some.
    fn has_credentials(&self, instance: &str) -> Result<bool> {
        Ok(self.get_credentials(instance)?.is_some())
    }
}

/// In-memory credential store for testing and temporary use.
///
/// Does NOT persist credentials across restarts. Useful for:
/// - Unit tests
/// - Temporary sessions
/// - WASM applications without localStorage access
///
/// # Example
///
/// ```rust
/// use kalam_client::credentials::{CredentialStore, Credentials, MemoryCredentialStore};
///
/// let mut store = MemoryCredentialStore::new();
/// let creds = Credentials::new("local".to_string(), "jwt.token.value".to_string());
///
/// store.set_credentials(&creds).unwrap();
/// let retrieved = store.get_credentials("local").unwrap();
/// assert_eq!(retrieved, Some(creds));
/// ```
#[derive(Debug, Default, Clone)]
pub struct MemoryCredentialStore {
    credentials: std::collections::HashMap<String, Credentials>,
}

impl MemoryCredentialStore {
    /// Create a new empty in-memory credential store
    pub fn new() -> Self {
        Self {
            credentials: std::collections::HashMap::new(),
        }
    }
}

impl CredentialStore for MemoryCredentialStore {
    fn get_credentials(&self, instance: &str) -> Result<Option<Credentials>> {
        Ok(self.credentials.get(instance).cloned())
    }

    fn set_credentials(&mut self, credentials: &Credentials) -> Result<()> {
        self.credentials.insert(credentials.instance.clone(), credentials.clone());
        Ok(())
    }

    fn delete_credentials(&mut self, instance: &str) -> Result<()> {
        self.credentials.remove(instance);
        Ok(())
    }

    fn list_instances(&self) -> Result<Vec<String>> {
        Ok(self.credentials.keys().cloned().collect())
    }
}

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

    #[test]
    fn test_credentials_creation() {
        let creds = Credentials::new(
            "local".to_string(),
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test".to_string(),
        );

        assert_eq!(creds.instance, "local");
        assert_eq!(creds.jwt_token, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test");
        assert_eq!(creds.user, None);
        assert_eq!(creds.expires_at, None);
        assert_eq!(creds.server_url, None);
        assert_eq!(creds.get_server_url(), "local");
    }

    #[test]
    fn test_credentials_with_details() {
        let creds = Credentials::with_details(
            "prod".to_string(),
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.test".to_string(),
            "alice".to_string(),
            "2025-12-31T23:59:59Z".to_string(),
            Some("https://db.example.com".to_string()),
        );

        assert_eq!(creds.instance, "prod");
        assert_eq!(creds.user, Some(UserId::from("alice")));
        assert_eq!(creds.expires_at, Some("2025-12-31T23:59:59Z".to_string()));
        assert_eq!(creds.server_url, Some("https://db.example.com".to_string()));
        assert_eq!(creds.get_server_url(), "https://db.example.com");
    }

    #[test]
    fn test_credentials_expiry_check() {
        // Expired token
        let expired_creds = Credentials::with_details(
            "test".to_string(),
            "token".to_string(),
            "user".to_string(),
            "2020-01-01T00:00:00Z".to_string(),
            None,
        );
        assert!(expired_creds.is_expired());

        // Future token
        let valid_creds = Credentials::with_details(
            "test".to_string(),
            "token".to_string(),
            "user".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            None,
        );
        assert!(!valid_creds.is_expired());

        // No expiry set (assume valid)
        let no_expiry = Credentials::new("test".to_string(), "token".to_string());
        assert!(!no_expiry.is_expired());
    }

    #[test]
    fn test_memory_store_basic_operations() {
        let mut store = MemoryCredentialStore::new();

        // Initially empty
        assert_eq!(store.get_credentials("local").unwrap(), None);
        assert!(!store.has_credentials("local").unwrap());

        // Store credentials
        let creds = Credentials::new("local".to_string(), "jwt_token_here".to_string());
        store.set_credentials(&creds).unwrap();

        // Retrieve credentials
        let retrieved = store.get_credentials("local").unwrap();
        assert_eq!(retrieved, Some(creds.clone()));
        assert!(store.has_credentials("local").unwrap());

        // Delete credentials
        store.delete_credentials("local").unwrap();
        assert_eq!(store.get_credentials("local").unwrap(), None);
    }

    #[test]
    fn test_memory_store_multiple_instances() {
        let mut store = MemoryCredentialStore::new();

        let creds1 = Credentials::with_details(
            "local".to_string(),
            "token1".to_string(),
            "alice".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            None,
        );
        let creds2 = Credentials::with_details(
            "prod".to_string(),
            "token2".to_string(),
            "bob".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            None,
        );
        let creds3 = Credentials::with_details(
            "dev".to_string(),
            "token3".to_string(),
            "carol".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            None,
        );

        store.set_credentials(&creds1).unwrap();
        store.set_credentials(&creds2).unwrap();
        store.set_credentials(&creds3).unwrap();

        // List instances
        let instances = store.list_instances().unwrap();
        assert_eq!(instances.len(), 3);
        assert!(instances.contains(&"local".to_string()));
        assert!(instances.contains(&"prod".to_string()));
        assert!(instances.contains(&"dev".to_string()));

        // Retrieve specific instances
        assert_eq!(
            store.get_credentials("local").unwrap().unwrap().user,
            Some(UserId::from("alice"))
        );
        assert_eq!(store.get_credentials("prod").unwrap().unwrap().user, Some(UserId::from("bob")));
        assert_eq!(
            store.get_credentials("dev").unwrap().unwrap().user,
            Some(UserId::from("carol"))
        );
    }

    #[test]
    fn test_memory_store_overwrite() {
        let mut store = MemoryCredentialStore::new();

        let creds1 = Credentials::new("local".to_string(), "old_token".to_string());
        let creds2 = Credentials::new("local".to_string(), "new_token".to_string());

        store.set_credentials(&creds1).unwrap();
        store.set_credentials(&creds2).unwrap();

        let retrieved = store.get_credentials("local").unwrap().unwrap();
        assert_eq!(retrieved.jwt_token, "new_token");
    }

    #[test]
    fn test_credentials_serialization() {
        let creds = Credentials::with_details(
            "prod".to_string(),
            "eyJhbGciOiJIUzI1NiJ9.test".to_string(),
            "alice".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            Some("https://db.example.com".to_string()),
        );

        // Serialize to JSON
        let json = serde_json::to_string(&creds).unwrap();

        // Deserialize back
        let deserialized: Credentials = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, creds);
    }

    #[test]
    fn test_credentials_with_refresh_token() {
        let creds = Credentials::with_refresh_token(
            "prod".to_string(),
            "access_token".to_string(),
            "alice".to_string(),
            "2099-01-01T00:00:00Z".to_string(),
            Some("https://db.example.com".to_string()),
            Some("refresh_token".to_string()),
            Some("2099-01-08T00:00:00Z".to_string()),
        );

        assert_eq!(creds.refresh_token, Some("refresh_token".to_string()));
        assert_eq!(creds.refresh_expires_at, Some("2099-01-08T00:00:00Z".to_string()));
        assert!(!creds.is_expired());
        assert!(!creds.is_refresh_expired());
        assert!(creds.can_refresh());
    }

    #[test]
    fn test_credentials_refresh_expired() {
        // Access token valid, but refresh token expired
        let creds = Credentials::with_refresh_token(
            "test".to_string(),
            "access_token".to_string(),
            "user".to_string(),
            "2099-12-31T23:59:59Z".to_string(),
            None,
            Some("old_refresh_token".to_string()),
            Some("2020-01-01T00:00:00Z".to_string()), // Expired
        );

        assert!(!creds.is_expired());
        assert!(creds.is_refresh_expired());
        assert!(!creds.can_refresh());
    }

    #[test]
    fn test_credentials_no_refresh_token() {
        // No refresh token at all
        let creds = Credentials::with_details(
            "test".to_string(),
            "access_token".to_string(),
            "user".to_string(),
            "2020-01-01T00:00:00Z".to_string(), // Expired access token
            None,
        );

        assert!(creds.is_expired());
        assert!(creds.is_refresh_expired()); // No refresh token = expired
        assert!(!creds.can_refresh());
    }
}