datafold 0.1.55

A personal database for data sovereignty with AI-powered ingestion
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
//! Security utility functions and helpers

use crate::{
    constants::SINGLE_PUBLIC_KEY_ID,
    security::{
        ConditionalEncryption, Ed25519KeyPair, Ed25519PublicKey, EncryptionManager,
        KeyRegistrationRequest, KeyRegistrationResponse, MessageVerifier, PublicKeyInfo,
        SecurityError, SecurityResult, SignedMessage,
    },
};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

/// Security manager that combines all security functionality
pub struct SecurityManager {
    /// Message verifier for signature verification
    pub verifier: Arc<MessageVerifier>,
    /// Conditional encryption for data at rest
    pub encryption: Arc<ConditionalEncryption>,
    /// Security configuration
    pub config: crate::security::SecurityConfig,
}

impl SecurityManager {
    /// Create a new security manager without persistence
    pub fn new(config: crate::security::SecurityConfig) -> SecurityResult<Self> {
        let verifier = Arc::new(MessageVerifier::new(300)); // 5 minute timestamp drift

        let encryption = Arc::new(ConditionalEncryption::new(
            config.encrypt_at_rest,
            config.master_key,
        )?);

        Ok(Self {
            verifier,
            encryption,
            config,
        })
    }

    /// Create a new security manager with database persistence
    pub async fn new_with_persistence(
        config: crate::security::SecurityConfig,
        db_ops: Arc<crate::db_operations::DbOperations>,
    ) -> SecurityResult<Self> {
        let verifier = Arc::new(MessageVerifier::new_with_persistence(300, db_ops).await?);

        let encryption = Arc::new(ConditionalEncryption::new(
            config.encrypt_at_rest,
            config.master_key,
        )?);

        Ok(Self {
            verifier,
            encryption,
            config,
        })
    }

    /// Register the system-wide public key
    pub async fn register_system_public_key(
        &self,
        request: KeyRegistrationRequest,
    ) -> SecurityResult<KeyRegistrationResponse> {
        // Validate the public key format
        let public_key = Ed25519PublicKey::from_base64(&request.public_key)
            .map_err(|e| SecurityError::InvalidPublicKey(e.to_string()))?;

        // Create public key info, using the validated and re-encoded key
        let mut key_info = PublicKeyInfo::new(
            SINGLE_PUBLIC_KEY_ID.to_string(),
            public_key.to_base64(), // Use the validated key, re-encoded
            request.owner_id,
            request.permissions,
        );

        // Add metadata
        for (k, v) in request.metadata {
            key_info = key_info.with_metadata(k, v);
        }

        // Set expiration if provided
        if let Some(expires_at) = request.expires_at {
            key_info = key_info.with_expiration(expires_at);
        }

        // Register with the verifier
        self.verifier
            .register_system_public_key(key_info.clone())
            .await?;

        Ok(KeyRegistrationResponse {
            success: true,
            public_key_id: Some(SINGLE_PUBLIC_KEY_ID.to_string()),
            key: Some(key_info),
            error: None,
        })
    }

    /// Verify a signed message
    pub fn verify_message(
        &self,
        signed_message: &SignedMessage,
    ) -> SecurityResult<crate::security::VerificationResult> {
        if !self.config.require_signatures {
            // If signatures are not required, create a mock successful result
            return Ok(crate::security::VerificationResult {
                is_valid: true,
                public_key_info: None,
                error: None,
                timestamp_valid: true,
            });
        }

        self.verifier.verify_message(signed_message)
    }

    /// Verify a message with required permissions
    pub fn verify_message_with_permissions(
        &self,
        signed_message: &SignedMessage,
        required_permissions: &[String],
    ) -> SecurityResult<crate::security::VerificationResult> {
        if !self.config.require_signatures {
            // If signatures are not required, create a mock successful result
            return Ok(crate::security::VerificationResult {
                is_valid: true,
                public_key_info: None,
                error: None,
                timestamp_valid: true,
            });
        }

        self.verifier
            .verify_message_with_permissions(signed_message, required_permissions)
    }

    /// Encrypt data if encryption is enabled
    pub fn encrypt_data(
        &self,
        data: &[u8],
    ) -> SecurityResult<Option<crate::security::EncryptedData>> {
        self.encryption.maybe_encrypt(data)
    }

    /// Encrypt JSON data if encryption is enabled
    pub fn encrypt_json(
        &self,
        json_data: &Value,
    ) -> SecurityResult<Option<crate::security::EncryptedData>> {
        self.encryption.maybe_encrypt_json(json_data)
    }

    /// Decrypt data
    pub fn decrypt_data(
        &self,
        encrypted_data: &crate::security::EncryptedData,
    ) -> SecurityResult<Vec<u8>> {
        self.encryption.maybe_decrypt(encrypted_data)
    }

    /// Decrypt JSON data
    pub fn decrypt_json(
        &self,
        encrypted_data: &crate::security::EncryptedData,
    ) -> SecurityResult<Value> {
        self.encryption.maybe_decrypt_json(encrypted_data)
    }

    /// Check if encryption is enabled
    pub fn is_encryption_enabled(&self) -> bool {
        self.encryption.is_encryption_enabled()
    }

    /// Get the system public key if it exists.
    pub fn get_system_public_key(&self) -> SecurityResult<Option<PublicKeyInfo>> {
        self.verifier.get_system_public_key()
    }

    /// Remove the system public key
    pub async fn remove_system_public_key(&self) -> SecurityResult<()> {
        self.verifier.remove_system_public_key().await
    }
}

/// Client-side security utilities
pub struct ClientSecurity;

impl ClientSecurity {
    /// Generate a new key pair for a client
    pub fn generate_client_keypair() -> SecurityResult<Ed25519KeyPair> {
        Ed25519KeyPair::generate()
    }

    /// Create a signer from a key pair
    pub fn create_signer(keypair: Ed25519KeyPair) -> crate::security::MessageSigner {
        crate::security::MessageSigner::new(keypair)
    }

    /// Create a key registration request
    pub fn create_registration_request(
        keypair: &Ed25519KeyPair,
        owner_id: String,
        permissions: Vec<String>,
    ) -> KeyRegistrationRequest {
        KeyRegistrationRequest {
            public_key: keypair.public_key_base64(),
            owner_id,
            permissions,
            metadata: HashMap::new(),
            expires_at: None,
        }
    }

    /// Create a signed message from a payload
    pub fn sign_message(
        signer: &crate::security::MessageSigner,
        payload: Value,
    ) -> SecurityResult<SignedMessage> {
        signer.sign_message(payload)
    }

    /// Generate example client code
    pub fn generate_client_example() -> String {
        r#"
// Example client-side usage
use datafold::security::*;

// 1. Generate a key pair
let keypair = ClientSecurity::generate_client_keypair()?;

// 2. Create a registration request
let registration_request = ClientSecurity::create_registration_request(
    &keypair,
    "system_owner".to_string(),
    vec!["read".to_string(), "write".to_string()],
);

// 3. Send registration request to server.
// The public key will be registered as the single system-wide key.
// let response = send_registration_request(registration_request).await?;

// 4. Create a message signer
let signer = ClientSecurity::create_signer(keypair);

// 5. Sign messages before sending to server
let payload = serde_json::json!({
    "action": "create_user",
    "data": {
        "username": "alice",
        "email": "alice@example.com"
    }
});

let signed_message = ClientSecurity::sign_message(&signer, payload)?;

// 6. Send signed message to server
// let response = send_signed_message(signed_message).await?;
"#
        .to_string()
    }
}

/// Server-side security middleware
pub struct SecurityMiddleware {
    manager: Arc<SecurityManager>,
}

impl SecurityMiddleware {
    /// Create new security middleware
    pub fn new(manager: Arc<SecurityManager>) -> Self {
        Self { manager }
    }

    /// Validate an incoming request
    pub fn validate_request(
        &self,
        signed_message: &SignedMessage,
        required_permissions: Option<&[String]>,
    ) -> SecurityResult<String> {
        let result = if let Some(perms) = required_permissions {
            self.manager
                .verify_message_with_permissions(signed_message, perms)?
        } else {
            self.manager.verify_message(signed_message)?
        };

        if !result.is_valid {
            return Err(SecurityError::SignatureVerificationFailed(
                result.error.unwrap_or("Invalid signature".to_string()),
            ));
        }

        if !result.timestamp_valid {
            return Err(SecurityError::SignatureVerificationFailed(
                "Invalid timestamp".to_string(),
            ));
        }

        // Return the owner ID if available
        Ok(result
            .public_key_info
            .map(|info| info.owner_id)
            .unwrap_or_else(|| "anonymous".to_string()))
    }

    /// Extract and validate a signed message from JSON
    pub fn extract_signed_message(&self, json_data: &Value) -> SecurityResult<SignedMessage> {
        serde_json::from_value(json_data.clone())
            .map_err(|e| SecurityError::DeserializationError(e.to_string()))
    }

    /// Wrap a response with optional encryption
    pub fn prepare_response(&self, response_data: &Value) -> SecurityResult<Value> {
        if let Some(encrypted) = self.manager.encrypt_json(response_data)? {
            // If encryption is enabled, return encrypted response
            Ok(serde_json::to_value(encrypted)
                .map_err(|e| SecurityError::SerializationError(e.to_string()))?)
        } else {
            // If encryption is disabled, return raw response
            Ok(response_data.clone())
        }
    }
}

/// Configuration helpers
pub struct SecurityConfigBuilder {
    config: crate::security::SecurityConfig,
}

impl SecurityConfigBuilder {
    /// Create a new config builder
    pub fn new() -> Self {
        Self {
            config: crate::security::SecurityConfig::default(),
        }
    }

    /// Set TLS requirement
    pub fn require_tls(mut self, require: bool) -> Self {
        self.config.require_tls = require;
        self
    }

    /// Set signature requirement
    pub fn require_signatures(mut self, require: bool) -> Self {
        self.config.require_signatures = require;
        self
    }

    /// Enable encryption with a generated key
    pub fn enable_encryption(mut self) -> Self {
        self.config.encrypt_at_rest = true;
        self.config.master_key = Some(EncryptionManager::generate_master_key());
        self
    }

    /// Enable encryption with a specific key
    pub fn enable_encryption_with_key(mut self, key: [u8; 32]) -> Self {
        self.config.encrypt_at_rest = true;
        self.config.master_key = Some(key);
        self
    }

    /// Enable encryption with a password-derived key
    pub fn enable_encryption_with_password(
        mut self,
        password: &str,
        salt: &[u8],
    ) -> SecurityResult<Self> {
        let key = crate::security::EncryptionUtils::derive_key_from_password(password, salt)?;
        self.config.encrypt_at_rest = true;
        self.config.master_key = Some(key);
        Ok(self)
    }

    /// Build the configuration
    pub fn build(self) -> crate::security::SecurityConfig {
        self.config
    }
}

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

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

    #[tokio::test]
    async fn test_security_manager() {
        // Test with default config (no encryption)
        let config = crate::security::SecurityConfig {
            require_tls: true,
            require_signatures: true,
            encrypt_at_rest: true,
            master_key: Some([0; 32]),
        };
        let manager = SecurityManager::new(config).unwrap();

        // Generate a client keypair
        let keypair = Ed25519KeyPair::generate().unwrap();

        // Register the public key
        let registration_request = crate::security::KeyRegistrationRequest {
            public_key: keypair.public_key_base64(),
            owner_id: "test_user".to_string(),
            permissions: vec!["read".to_string()],
            metadata: std::collections::HashMap::new(),
            expires_at: None,
        };

        let response = manager
            .register_system_public_key(registration_request)
            .await
            .unwrap();
        assert!(response.success);
        assert!(response.public_key_id.is_some());
    }

    #[tokio::test]
    async fn test_security_middleware() {
        // Test with default config
        let config = crate::security::SecurityConfig {
            require_tls: true,
            require_signatures: true,
            encrypt_at_rest: true,
            master_key: Some([0; 32]),
        };
        let manager = Arc::new(SecurityManager::new(config).unwrap());
        let middleware = SecurityMiddleware::new(manager.clone());

        // Generate a client keypair
        let keypair = Ed25519KeyPair::generate().unwrap();

        // Register the public key
        let registration_request = crate::security::KeyRegistrationRequest {
            public_key: keypair.public_key_base64(),
            owner_id: "test_user".to_string(),
            permissions: vec!["read".to_string()],
            metadata: std::collections::HashMap::new(),
            expires_at: None,
        };

        let response = manager
            .register_system_public_key(registration_request)
            .await
            .unwrap();
        let _public_key_id = response.public_key_id.unwrap();

        // Create a signed message
        let signer = ClientSecurity::create_signer(keypair);
        let payload = serde_json::json!({"action": "test"});
        let signed_message = ClientSecurity::sign_message(&signer, payload).unwrap();

        // Validate the request
        let owner_id = middleware
            .validate_request(&signed_message, Some(&["read".to_string()]))
            .unwrap();
        assert_eq!(owner_id, "test_user");

        // Test with missing permissions
        let result = middleware.validate_request(&signed_message, Some(&["write".to_string()]));
        assert!(result.is_err());
    }

    #[test]
    fn test_config_builder() {
        let config = SecurityConfigBuilder::new()
            .require_tls(true)
            .require_signatures(true)
            .enable_encryption()
            .build();

        assert!(config.require_tls);
        assert!(config.require_signatures);
        assert!(config.encrypt_at_rest);
        assert!(config.master_key.is_some());
    }
}