fortress-db 0.1.0

A highly customizable, secure database system with multi-layer encryption
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# Fortress API Usage Examples

This repository contains practical examples of using the Fortress REST API with various programming languages and use cases.

## Quick Start

1. Start the Fortress server:
```bash
cargo run --bin fortress-server
```

2. The server will be available at `http://localhost:8080`

## Examples

### 1. Basic Data Storage and Retrieval

#### Python
```python
import requests
import json
import time

BASE_URL = "http://localhost:8080"

class FortressClient:
    def __init__(self, base_url=BASE_URL):
        self.base_url = base_url
        self.session = requests.Session()
    
    def store_data(self, data, metadata=None):
        """Store encrypted data"""
        payload = {
            "data": data,
            "metadata": metadata or {}
        }
        
        response = self.session.post(
            f"{self.base_url}/data",
            json=payload
        )
        return response.json()
    
    def retrieve_data(self, data_id):
        """Retrieve and decrypt data"""
        response = self.session.get(f"{self.base_url}/data/{data_id}")
        return response.json()
    
    def delete_data(self, data_id):
        """Delete data"""
        response = self.session.delete(f"{self.base_url}/data/{data_id}")
        return response.json()
    
    def list_data(self):
        """List all stored data"""
        response = self.session.get(f"{self.base_url}/data")
        return response.json()

# Usage example
def main():
    client = FortressClient()
    
    # Store user profile
    user_data = {
        "name": "Alice Johnson",
        "email": "alice@example.com",
        "age": 28,
        "preferences": {
            "theme": "dark",
            "notifications": True
        }
    }
    
    print("Storing user data...")
    store_result = client.store_data(
        user_data,
        metadata={"type": "user_profile", "version": "1.0"}
    )
    
    if store_result["success"]:
        data_id = store_result["data"]["id"]
        print(f"Data stored with ID: {data_id}")
        
        # Retrieve the data
        print("Retrieving data...")
        retrieve_result = client.retrieve_data(data_id)
        
        if retrieve_result["success"]:
            retrieved_data = retrieve_result["data"]["data"]
            print(f"Retrieved user: {retrieved_data['name']}")
            print(f"Email: {retrieved_data['email']}")
        
        # List all data
        print("Listing all data...")
        list_result = client.list_data()
        if list_result["success"]:
            print(f"Total items: {len(list_result['data'])}")

if __name__ == "__main__":
    main()
```

#### JavaScript/Node.js
```javascript
const axios = require('axios');

class FortressClient {
    constructor(baseUrl = 'http://localhost:8080') {
        this.baseUrl = baseUrl;
        this.client = axios.create({
            baseURL: baseUrl,
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }

    async storeData(data, metadata = {}) {
        try {
            const response = await this.client.post('/data', {
                data,
                metadata
            });
            return response.data;
        } catch (error) {
            console.error('Store error:', error.response?.data || error.message);
            throw error;
        }
    }

    async retrieveData(dataId) {
        try {
            const response = await this.client.get(`/data/${dataId}`);
            return response.data;
        } catch (error) {
            console.error('Retrieve error:', error.response?.data || error.message);
            throw error;
        }
    }

    async deleteData(dataId) {
        try {
            const response = await this.client.delete(`/data/${dataId}`);
            return response.data;
        } catch (error) {
            console.error('Delete error:', error.response?.data || error.message);
            throw error;
        }
    }

    async listData() {
        try {
            const response = await this.client.get('/data');
            return response.data;
        } catch (error) {
            console.error('List error:', error.response?.data || error.message);
            throw error;
        }
    }
}

// Usage example
async function main() {
    const client = new FortressClient();

    try {
        // Store encrypted document
        const document = {
            title: 'Confidential Report',
            content: 'This is a secret document that will be encrypted automatically.',
            classification: 'confidential',
            author: 'John Doe',
            created: new Date().toISOString()
        };

        console.log('Storing document...');
        const storeResult = await client.storeData(
            document,
            { type: 'document', classification: 'confidential' }
        );

        if (storeResult.success) {
            const docId = storeResult.data.id;
            console.log(`Document stored with ID: ${docId}`);

            // Retrieve the document
            console.log('Retrieving document...');
            const retrieveResult = await client.retrieveData(docId);

            if (retrieveResult.success) {
                const doc = retrieveResult.data.data;
                console.log(`Retrieved: ${doc.title}`);
                console.log(`Classification: ${doc.classification}`);
                console.log(`Content length: ${doc.content.length} characters`);
            }
        }

        // List all documents
        console.log('Listing all data...');
        const listResult = await client.listData();
        if (listResult.success) {
            console.log(`Total items stored: ${listResult.data.length}`);
        }

    } catch (error) {
        console.error('Error:', error.message);
    }
}

main();
```

### 2. Field-Level Encryption

#### Python
```python
import requests
import json

BASE_URL = "http://localhost:8080"

def store_sensitive_user_data():
    """Store user data with field-level encryption for sensitive fields"""
    
    user_data = {
        "name": "Bob Smith",
        "email": "bob.smith@example.com",
        "phone": "+1-555-0123",
        "ssn": "123-45-6789",  # This will be encrypted with separate key
        "address": "123 Main St, Anytown, USA",
        "preferences": {
            "theme": "light",
            "newsletter": True
        }
    }
    
    # Configure field-level encryption for sensitive fields
    field_encryption = {
        "fields": {
            "ssn": {
                "algorithm": "aes256gcm",
                "key_id": "ssn-encryption-key",
                "sensitivity": "critical"
            },
            "phone": {
                "algorithm": "aes256gcm", 
                "key_id": "phone-encryption-key",
                "sensitivity": "high"
            }
        }
    }
    
    payload = {
        "data": user_data,
        "field_encryption": field_encryption,
        "metadata": {
            "type": "user_profile",
            "contains_pii": True,
            "field_encryption_enabled": True
        }
    }
    
    response = requests.post(f"{BASE_URL}/data", json=payload)
    result = response.json()
    
    if result["success"]:
        print("User data stored with field-level encryption")
        print(f"Data ID: {result['data']['id']}")
        
        # Show field encryption metadata
        field_metadata = result["data"]["field_metadata"]
        for field, meta in field_metadata.items():
            print(f"Field '{field}' encrypted with algorithm: {meta['algorithm']}")
    
    return result

if __name__ == "__main__":
    store_sensitive_user_data()
```

### 3. Authentication Flow

#### JavaScript
```javascript
const axios = require('axios');

class FortressAuthClient {
    constructor(baseUrl = 'http://localhost:8080') {
        this.baseUrl = baseUrl;
        this.token = null;
        this.client = axios.create({
            baseURL: baseUrl,
            timeout: 30000
        });
    }

    async login(username, password, tenantId = null) {
        try {
            const response = await this.client.post('/auth/login', {
                username,
                password,
                tenant_id: tenantId
            });
            
            if (response.data.success) {
                this.token = response.data.data.token;
                this.setupAuthenticatedClient();
                return response.data;
            }
            throw new Error('Login failed');
        } catch (error) {
            console.error('Login error:', error.response?.data || error.message);
            throw error;
        }
    }

    setupAuthenticatedClient() {
        this.client.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;
    }

    async refreshToken() {
        try {
            const response = await this.client.post('/auth/refresh', {
                token: this.token
            });
            
            if (response.data.success) {
                this.token = response.data.data.token;
                this.setupAuthenticatedClient();
                return response.data;
            }
            throw new Error('Token refresh failed');
        } catch (error) {
            console.error('Refresh error:', error.response?.data || error.message);
            throw error;
        }
    }

    async storeAuthenticatedData(data) {
        if (!this.token) {
            throw new Error('Not authenticated');
        }
        
        try {
            const response = await this.client.post('/data', { data });
            return response.data;
        } catch (error) {
            if (error.response?.status === 401) {
                // Token expired, try refresh
                await this.refreshToken();
                return await this.client.post('/data', { data });
            }
            throw error;
        }
    }
}

// Usage example
async function authExample() {
    const authClient = new FortressAuthClient();

    try {
        // Login
        console.log('Logging in...');
        const loginResult = await authClient.login('alice', 'secure-password-123');
        
        if (loginResult.success) {
            console.log('Login successful!');
            console.log(`Token expires: ${loginResult.data.expires_at}`);
            
            // Store authenticated data
            const secretData = {
                message: 'This data requires authentication to access',
                user_id: loginResult.data.user.id,
                timestamp: new Date().toISOString()
            };
            
            console.log('Storing authenticated data...');
            const storeResult = await authClient.storeAuthenticatedData(secretData);
            
            if (storeResult.success) {
                console.log('Authenticated data stored successfully');
                console.log(`Data ID: ${storeResult.data.id}`);
            }
        }

    } catch (error) {
        console.error('Authentication error:', error.message);
    }
}

authExample();
```

### 4. Bulk Operations

#### Rust
```rust
use reqwest;
use serde_json::json;
use tokio;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let base_url = "http://localhost:8080";
    
    // Generate multiple records to store
    let records: Vec<serde_json::Value> = (1..=10)
        .map(|i| {
            json!({
                "data": {
                    "id": i,
                    "name": format!("Record {}", i),
                    "value": i * 10,
                    "timestamp": chrono::Utc::now().to_rfc3339()
                },
                "metadata": {
                    "batch_id": "bulk-import-001",
                    "source": "example-script"
                }
            })
        })
        .collect();
    
    let mut stored_ids = Vec::new();
    
    // Store all records concurrently
    let mut tasks = Vec::new();
    
    for record in records {
        let client = client.clone();
        let url = format!("{}/data", base_url);
        
        let task = tokio::spawn(async move {
            match client.post(&url).json(&record).send().await {
                Ok(response) => {
                    match response.json::<serde_json::Value>() {
                        Ok(result) => {
                            if result["success"].as_bool().unwrap_or(false) {
                                Some(result["data"]["id"].as_str().unwrap().to_string())
                            } else {
                                None
                            }
                        }
                        Err(e) => {
                            eprintln!("Error parsing response: {}", e);
                            None
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error storing record: {}", e);
                    None
                }
            }
        });
        
        tasks.push(task);
    }
    
    // Wait for all tasks to complete
    let results = futures::future::join_all(tasks).await;
    
    for result in results {
        if let Ok(Some(id)) = result {
            stored_ids.push(id);
        }
    }
    
    println!("Successfully stored {} records", stored_ids.len());
    
    // Retrieve all records to verify
    let list_response = client.get(&format!("{}/data", base_url))
        .send()
        .await?;
    
    let list_result: serde_json::Value = list_response.json().await?;
    
    if list_result["success"].as_bool().unwrap_or(false) {
        let total_items = list_result["data"].as_array().unwrap().len();
        println!("Total items in database: {}", total_items);
    }
    
    Ok(())
}
```

### 5. Error Handling and Retry Logic

#### Python
```python
import requests
import time
import json
from typing import Optional, Dict, Any

class FortressClientWithRetry:
    def __init__(self, base_url: str = "http://localhost:8080", max_retries: int = 3):
        self.base_url = base_url
        self.max_retries = max_retries
        self.session = requests.Session()
    
    def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
        """Make request with retry logic"""
        url = f"{self.base_url}{endpoint}"
        
        for attempt in range(self.max_retries + 1):
            try:
                response = self.session.request(method, url, **kwargs)
                
                if response.status_code == 200:
                    return response.json()
                elif response.status_code == 429:
                    # Rate limited - wait and retry
                    retry_after = int(response.headers.get('Retry-After', 1))
                    print(f"Rate limited. Waiting {retry_after} seconds...")
                    time.sleep(retry_after)
                    continue
                elif response.status_code >= 500:
                    # Server error - retry
                    if attempt < self.max_retries:
                        wait_time = 2 ** attempt  # Exponential backoff
                        print(f"Server error. Retrying in {wait_time} seconds...")
                        time.sleep(wait_time)
                        continue
                
                # Non-retryable error
                return response.json()
                
            except requests.exceptions.RequestException as e:
                if attempt < self.max_retries:
                    wait_time = 2 ** attempt
                    print(f"Network error. Retrying in {wait_time} seconds...")
                    time.sleep(wait_time)
                    continue
                raise
        
        raise Exception(f"Max retries ({self.max_retries}) exceeded")
    
    def store_data(self, data: Dict[str, Any], metadata: Optional[Dict[str, Any]] = None):
        """Store data with retry logic"""
        return self._make_request(
            'POST',
            '/data',
            json={'data': data, 'metadata': metadata or {}}
        )
    
    def retrieve_data(self, data_id: str):
        """Retrieve data with retry logic"""
        return self._make_request('GET', f'/data/{data_id}')

# Usage example
def robust_example():
    client = FortressClientWithRetry(max_retries=5)
    
    # Store data with automatic retry
    print("Storing data with retry logic...")
    try:
        result = client.store_data({
            "message": "This will be stored reliably",
            "timestamp": time.time()
        })
        
        if result["success"]:
            print("Data stored successfully!")
            data_id = result["data"]["id"]
            
            # Retrieve with retry
            print("Retrieving data...")
            retrieved = client.retrieve_data(data_id)
            
            if retrieved["success"]:
                print("Data retrieved successfully!")
                print(f"Content: {retrieved['data']['data']['message']}")
        
    except Exception as e:
        print(f"Operation failed after retries: {e}")

if __name__ == "__main__":
    robust_example()
```

### 6. Monitoring and Metrics

#### JavaScript
```javascript
const axios = require('axios');

class FortressMonitor {
    constructor(baseUrl = 'http://localhost:8080') {
        this.baseUrl = baseUrl;
        this.client = axios.create({ baseURL: baseUrl });
    }

    async getMetrics() {
        try {
            const response = await this.client.get('/metrics');
            return response.data;
        } catch (error) {
            console.error('Error fetching metrics:', error.message);
            throw error;
        }
    }

    async getPrometheusMetrics() {
        try {
            const response = await this.client.get('/metrics/prometheus');
            return response.data;
        } catch (error) {
            console.error('Error fetching Prometheus metrics:', error.message);
            throw error;
        }
    }

    async getHealthStatus() {
        try {
            const response = await this.client.get('/health');
            return response.data;
        } catch (error) {
            console.error('Error checking health:', error.message);
            throw error;
        }
    }

    async monitorServer(intervalMs = 30000) {
        console.log(`Starting server monitoring (interval: ${intervalMs}ms)`);
        
        const monitor = async () => {
            try {
                // Check health
                const health = await this.getHealthStatus();
                console.log(`Health Status: ${health.data.status}`);
                
                // Get metrics
                const metrics = await this.getMetrics();
                console.log(`Total Requests: ${metrics.metrics.requests_total}`);
                console.log(`Success Rate: ${((metrics.metrics.requests_success / metrics.metrics.requests_total) * 100).toFixed(2)}%`);
                console.log(`Avg Response Time: ${metrics.metrics.response_time_avg_ms}ms`);
                
            } catch (error) {
                console.error('Monitoring error:', error.message);
            }
        };
        
        // Initial check
        monitor();
        
        // Set up interval
        return setInterval(monitor, intervalMs);
    }
}

// Usage example
async function startMonitoring() {
    const monitor = new FortressMonitor();
    
    try {
        // Get current metrics
        console.log('Fetching current metrics...');
        const metrics = await monitor.getMetrics();
        console.log('Current Metrics:', metrics);
        
        // Get Prometheus metrics for monitoring systems
        console.log('Fetching Prometheus metrics...');
        const prometheus = await monitor.getPrometheusMetrics();
        console.log('Prometheus Metrics (first 500 chars):');
        console.log(prometheus.substring(0, 500));
        
        // Start continuous monitoring
        console.log('Starting continuous monitoring...');
        monitor.monitorServer(10000); // Monitor every 10 seconds
        
    } catch (error) {
        console.error('Monitoring setup failed:', error.message);
    }
}

startMonitoring();
```

## Running the Examples

1. **Python Examples**:
   ```bash
   cd examples/python
   pip install -r requirements.txt
   python basic_usage.py
   ```

2. **JavaScript Examples**:
   ```bash
   cd examples/javascript
   npm install
   node basic_usage.js
   ```

3. **Rust Examples**:
   ```bash
   cd examples/rust
   cargo run --example bulk_operations
   ```

## Best Practices

1. **Always handle errors gracefully** - Check the `success` field in responses
2. **Implement retry logic** - Network requests can fail temporarily
3. **Use field-level encryption** for sensitive data like SSN, credit cards
4. **Monitor rate limits** - Respect `X-RateLimit-*` headers
5. **Secure your tokens** - Store JWT tokens securely and refresh before expiry
6. **Validate input** - Ensure data is properly formatted before sending
7. **Use appropriate algorithms** - AEGIS-256 for speed, AES-256-GCM for compatibility

## Troubleshooting

### Common Issues

1. **Connection refused**: Make sure the Fortress server is running
2. **Authentication errors**: Check your credentials and token format
3. **Rate limiting**: Implement backoff and retry logic
4. **Large payloads**: Check `max_body_size` configuration
5. **Field encryption errors**: Verify algorithm names and key IDs

### Debug Mode

Enable debug logging by setting the `RUST_LOG` environment variable:

```bash
export RUST_LOG=debug
cargo run --bin fortress-server
```

This will provide detailed logging for troubleshooting API issues.