# Cloud Backup Architecture Documentation

## Current Implementation (Firebase-based)

### Data Flow & Encryption Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                     LOCAL DEVICE (App)                       │
├─────────────────────────────────────────────────────────────┤
│ 1. SQLite Database (Unencrypted or AES-256 encrypted)       │
│    ├── Weight Entries                                        │
│    ├── Blood Pressure Entries                                │
│    └── Mood Entries                                          │
│                                                               │
│ 2. Data Export (performBackup)                               │
│    └── Extract all data from SQLite                          │
│                                                               │
│ 3. JSON Serialization                                        │
│    └── Convert to JSON structure                             │
│                                                               │
│ 4. CLIENT-SIDE ENCRYPTION (AES-256-GCM)                     │
│    ├── Generate random IV (16 bytes)                         │
│    ├── Encrypt JSON data                                     │
│    ├── Calculate SHA-256 checksum                            │
│    └── Result: Encrypted binary blob                         │
│                                                               │
│ 5. Upload to Cloud                                           │
│    └── Send encrypted blob over HTTPS/TLS                    │
└─────────────────────────────────────────────────────────────┘
                              ↓
                    HTTPS/TLS Connection
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                    CLOUD STORAGE (Firebase)                  │
├─────────────────────────────────────────────────────────────┤
│ • Firebase Storage: Stores encrypted blob as binary file     │
│ • Firestore: Stores metadata (not the actual health data)    │
│ • Data remains encrypted at rest                             │
│ • No decryption keys stored in cloud                         │
└─────────────────────────────────────────────────────────────┘
```

### Current Encryption Details

#### When Encryption Happens
1. **Local Database**: Optional AES-256 encryption (if enabled)
2. **Before Upload**: ALWAYS encrypted on device using AES-256-GCM
3. **During Transfer**: TLS/HTTPS encryption (transport layer)
4. **Cloud Storage**: Encrypted blob stored (no additional cloud encryption)

#### Encryption Process (Line 154-155 in CloudBackupService)
```dart
final jsonData = jsonEncode(backupData);
final encryptedData = await _encryption.encryptData(jsonData);
```

#### Key Management
- **Encryption Key**: Derived from user password using PBKDF2 (100,000 iterations)
- **Key Storage**: Stored locally in secure storage (flutter_secure_storage)
- **Cloud**: NO encryption keys are sent to cloud
- **Recovery**: User must remember password; no key recovery mechanism

### Security Model
- **End-to-End Encryption**: Data encrypted on device, remains encrypted in cloud
- **Zero-Knowledge**: Cloud provider cannot decrypt data
- **Authentication**: Anonymous Firebase auth (no personal info required)
- **Access Control**: User ID-based isolation in cloud storage

## AWS Alternative Architectures

### Option 1: Direct S3 Storage with Client-Side Encryption (Recommended)

```
┌─────────────────────────────────────────────────────────────┐
│                     LOCAL DEVICE (App)                       │
├─────────────────────────────────────────────────────────────┤
│ Same encryption process as current (AES-256-GCM)             │
│                                                               │
│ AWS SDK Operations:                                          │
│ • AWS Amplify or AWS SDK for Dart                           │
│ • Cognito for anonymous authentication                       │
│ • Direct S3 upload with pre-signed URLs                      │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                        AWS SERVICES                          │
├─────────────────────────────────────────────────────────────┤
│ • Cognito Identity Pool (anonymous auth)                     │
│ • S3 Bucket (encrypted blob storage)                         │
│ • DynamoDB (metadata storage)                                │
│ • CloudWatch (monitoring/logs)                               │
└─────────────────────────────────────────────────────────────┘
```

**Advantages:**
- Client-side encryption maintained
- No server infrastructure needed
- Cost-effective for small scale
- Direct S3 integration

**Implementation:**
```dart
// Example AWS S3 upload with client-side encryption
class AWSBackupService {
  Future<void> uploadBackup(String encryptedData) async {
    final s3Client = S3Client(
      region: 'us-east-1',
      credentials: await _getCognitoCredentials(),
    );
    
    await s3Client.putObject(
      bucket: 'health-tracker-backups',
      key: 'users/$userId/backup.encrypted',
      body: encryptedData.codeUnits,
      metadata: {
        'checksum': calculateSHA256(encryptedData),
        'encrypted': 'true',
        'timestamp': DateTime.now().toIso8601String(),
      },
    );
  }
}
```

### Option 2: S3 with Server-Side Encryption (SSE)

```
┌─────────────────────────────────────────────────────────────┐
│                     LOCAL DEVICE (App)                       │
├─────────────────────────────────────────────────────────────┤
│ TWO OPTIONS:                                                 │
│                                                               │
│ A) Double Encryption:                                        │
│    • Client-side AES-256 + S3 SSE-KMS                       │
│                                                               │
│ B) S3 SSE Only:                                             │
│    • Send unencrypted over TLS                              │
│    • S3 encrypts at rest with SSE-KMS                       │
└─────────────────────────────────────────────────────────────┘
```

**S3 Encryption Options:**
1. **SSE-S3**: S3 managed keys (AES-256)
2. **SSE-KMS**: AWS KMS managed keys (more control, audit trail)
3. **SSE-C**: Customer provided keys (complex key management)

### Option 3: Serverless Backend with Lambda

```
┌─────────────────────────────────────────────────────────────┐
│              SERVERLESS ARCHITECTURE                         │
├─────────────────────────────────────────────────────────────┤
│ • API Gateway → Lambda → S3/DynamoDB                        │
│ • Additional processing/validation                           │
│ • Can implement versioning, deduplication                    │
│ • More complex but more flexible                            │
└─────────────────────────────────────────────────────────────┘
```

## AWS Services Comparison

| Service | Purpose | Cost | Security Features |
|---------|---------|------|-------------------|
| **S3** | Blob storage | $0.023/GB/month | SSE, versioning, lifecycle policies |
| **DynamoDB** | Metadata | $0.25/GB/month | Encryption at rest, point-in-time recovery |
| **Cognito** | Authentication | Free tier: 50K MAU | Anonymous auth, MFA support |
| **KMS** | Key management | $1/month per key | Key rotation, audit logs |
| **CloudWatch** | Monitoring | Free tier available | Alarms, logs, metrics |

## Implementation Recommendations

### For Privacy-First Approach (Current Model)
```yaml
Architecture: Client-side encryption + S3
Services:
  - Cognito Identity Pool (anonymous auth)
  - S3 (encrypted blob storage)
  - DynamoDB (metadata only)
  
Benefits:
  - Zero-knowledge architecture
  - User controls encryption keys
  - Cloud provider cannot access data
  
Drawbacks:
  - No password recovery (lost password = lost data)
  - Client responsible for key management
```

### For Convenience-First Approach
```yaml
Architecture: S3 with SSE-KMS
Services:
  - Cognito User Pools (with MFA)
  - S3 with SSE-KMS
  - DynamoDB
  - Lambda for processing
  
Benefits:
  - Password recovery possible
  - Server-side features (dedup, compression)
  - Audit trail via CloudTrail
  
Drawbacks:
  - AWS can technically decrypt data
  - More complex, higher cost
```

## Cost Estimation (AWS)

### Small Scale (100 users)
```
S3 Storage: 100 users × 10MB = 1GB = $0.023/month
DynamoDB: Metadata = $0.25/month
Cognito: Free tier
Data Transfer: 1GB/month = $0.09
Total: ~$0.36/month
```

### Medium Scale (10,000 users)
```
S3 Storage: 10,000 × 10MB = 100GB = $2.30/month
DynamoDB: On-demand = ~$5/month
Cognito: Free tier (under 50K MAU)
Data Transfer: 100GB/month = $9
Total: ~$16.30/month
```

## Security Considerations

### Current Implementation Strengths
1. **End-to-end encryption**: Data encrypted before leaving device
2. **Zero-knowledge**: Cloud provider cannot decrypt
3. **Checksum verification**: Data integrity protected
4. **Anonymous auth**: No PII required

### Potential Improvements for AWS
1. **Key rotation**: Implement periodic key rotation
2. **Versioning**: S3 versioning for backup history
3. **MFA**: Optional multi-factor authentication
4. **Audit logging**: CloudTrail for compliance
5. **Backup redundancy**: Cross-region replication

## Migration Path to AWS

### Phase 1: Infrastructure Setup
```bash
# AWS CLI setup
aws s3 mb s3://health-tracker-backups
aws cognito-identity create-identity-pool \
  --identity-pool-name HealthTrackerPool \
  --allow-unauthenticated-identities
```

### Phase 2: Code Refactoring
1. Replace Firebase SDK with AWS SDK
2. Update authentication flow (Firebase Auth → Cognito)
3. Update storage calls (Firebase Storage → S3)
4. Update metadata store (Firestore → DynamoDB)

### Phase 3: Testing & Migration
1. Parallel operation (both Firebase and AWS)
2. Gradual user migration
3. Data verification
4. Sunset Firebase infrastructure

## Summary

### Current Architecture
- **Encryption**: Client-side AES-256-GCM
- **When**: Before upload (always encrypted in cloud)
- **Where**: On device, not in cloud
- **Keys**: Never sent to cloud
- **Storage**: Firebase Storage (encrypted blobs)

### Recommended AWS Architecture
- **Services**: Cognito + S3 + DynamoDB
- **Encryption**: Client-side + optional SSE-KMS
- **Cost**: Minimal for personal use (~$1/month)
- **Benefits**: Better control, scalability, AWS ecosystem

The current implementation provides strong privacy protection through client-side encryption. The data is ALWAYS encrypted before leaving the device, making it a true zero-knowledge backup system where the cloud provider cannot access the actual health data.
