# Security, Cryptography & Data Sovereignty {#security-cryptography--data-sovereignty}


The **MQUAD** mobile field app handles highly sensitive socio-demographic, clinical, and human-subject research data. To comply with rigorous research ethics standards, GDPR, HIPAA, and national data sovereignty regulations, the client enforces a multi-tiered defense-in-depth security model.

---


## 1. Security Architecture Model {#1-security-architecture-model}






```mermaid
graph TD
    subgraph UI & Session Guard
        Bio[Biometric & PIN Gate] --> AppShield[App Switcher Blur & Screenshot Blocker]
        AppShield --> Inactivity[Session Timeout Manager]
    end

    subgraph Memory & Key Tier
        Keystore[Android Keystore / iOS Keychain] --> FSS[FlutterSecureStorage]
        FSS --> MasterKey[256-bit DB Encryption Key]
        FSS --> Tokens[Multi-Tenant JWT Tokens]
    end

    subgraph Data-at-Rest Tier
        MasterKey --> Cipher[SQLCipher AES-256 Engine]
        Cipher --> DriftDB[(Encrypted SQLite Database)]
        DriftDB --> Forms[Responses & Paradata]
    end

    subgraph Compliance & Policy Engine
        Policy[PolicyResolutionEngine] --> Lease[45-Day Offline Lease Gate]
        Policy --> RootCheck[Root / Jailbreak Detection]
    end
```





---


## 2. Cryptographic Storage at Rest {#2-cryptographic-storage-at-rest}


All local data—including survey schemas, draft responses, completed interviews, paradata, and audit logs—is stored in an encrypted database managed via **Drift** and **SQLCipher**.


### Database Encryption Specifications: {#database-encryption-specifications}
- **Cipher Algorithm**: AES-256 in CBC mode (Cipher Block Chaining).
- **Key Derivation Function (KDF)**: PBKDF2 with HMAC-SHA512.
- **Iteration Count**: 256,000 rounds.
- **Page Size**: 4096 bytes with per-page initialization vectors (IVs).
- **HMAC Verification**: Per-page integrity checking ensures that bit-level tampering causes a decryption fault rather than silent data corruption.

```dart
// Database Connection Initialization with SQLCipher
LazyDatabase openEncryptedConnection(String encryptionKey) {
  return LazyDatabase(() async {
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'mquad_encrypted.db'));
    
    return NativeDatabase.createInBackground(
      file,
      setup: (rawDb) {
        rawDb.execute("PRAGMA key = '$encryptionKey';");
        rawDb.execute("PRAGMA cipher_compatibility = 4;");
        rawDb.execute("PRAGMA cipher_page_size = 4096;");
        rawDb.execute("PRAGMA kdf_iter = 256000;");
      },
    );
  });
}
```

---


## 3. Hardware-Backed Key Storage {#3-hardware-backed-key-storage}


Database encryption keys and user authentication tokens are never stored as plaintext in application memory or shared preferences. Instead, MQUAD integrates with device secure hardware modules:

| Platform | Hardware Abstraction | Storage Mechanism | Security Attribute |
|----------|----------------------|-------------------|-------------------|
| **Android** | Hardware-backed Keymaster / StrongBox | Android Keystore | AES-256 GCM master key protecting encrypted preferences |
| **iOS** | Secure Enclave | Apple Keychain | `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` |
| **macOS** | Keychain Services | Apple Keychain | Scoped application sandbox keychain |
| **Windows** | Windows Credential Manager | DPAPI (Data Protection API) | Scoped user account encryption |
| **Linux** | Secret Service API / libsecret | GNOME Keyring / KWallet | User-authenticated keyring daemon |

---


## 4. Multi-Tenant Token Security {#4-multi-tenant-token-security}


MQUAD employs token authentication tailored for multi-organization environments:

1. **Multi-Tenant Token Format**:
   - The token contains `tenant_id: null` in its base claims.
   - The array `tenant_ids: ["uuid1", "uuid2", ...]` lists every workspace the user has permission to collect data for.
2. **Dynamic Header Injection**:
   - The networking layer (`Dio` client interceptor) injects `Authorization: Bearer <token>` and `X-Tenant-ID: <active_tenant_id>` per request.
3. **Automatic Refresh Rotation**:
   - When access tokens near expiration, `TokenRefreshInterceptor` seamlessly requests a new token pair using the long-lived refresh token stored in secure storage.
   - On logout or account revocation, both access and refresh tokens are wiped immediately from hardware secure storage.

---


## 5. Device Integrity & Anti-Tampering {#5-device-integrity--anti-tampering}


The `DeviceSecurityService` and `DeviceSecurityGate` verify device integrity prior to unlocking survey data:


### Integrity Controls: {#integrity-controls}
- **Root & Jailbreak Detection**: Checks for su binaries, Magisk hide indicators, unauthorized Cydia/Sileo packages, and accessible system partitions. If rooted, the app can be configured to warn the user or lock questionnaire submission.
- **Screenshot & Screen Recording Prevention**:
  - Android: `FLAG_SECURE` is active across all survey and response screens to prevent screen recording, screenshots, and remote casting.
  - iOS: Obfuscation canvas displays when a screen recording is detected.
- **App Switcher Privacy Curtain**: When the user backgrounds the application or enters the OS task manager, a privacy curtain widget is displayed, obscuring sensitive clinical and survey data from OS snapshots.

---


## 6. Session Lifecycle & Inactivity Gate {#6-session-lifecycle--inactivity-gate}


Field enumerators frequently leave tablets unattended while interacting with respondents or moving between households.

- **`SessionTimeoutManager`**: Listens for touch, scroll, and keyboard events across the entire widget tree using `Listener` and `GestureDetector` hooks.
- **Inactivity Timeout**: Configurable interval (default: 15 minutes of inactivity).
- **Lock Screen**: Triggers a full-screen biometric or PIN unlock overlay.
- **Biometric Integration**: Utilizes `local_auth` to authenticate using Touch ID, Face ID, or Android BiometricPrompt (Class 3 strong biometric).

---


## 7. 45-Day Offline Cryptographic Lease {#7-45-day-offline-cryptographic-lease}


To prevent field devices with cached questionnaires and sensitive responses from remaining indefinitely unmonitored in the field, MQUAD implements an **Offline Cryptographic Lease**:





```mermaid
sequenceDiagram
    participant Device as Mobile App
    participant Server as MQUAD Backend

    Device->>Server: Authenticate & Request Survey Catalog
    Server-->>Device: Issue Survey Schemas + Cryptographic Lease Token (45-day TTL)
    Note over Device: Device operates offline<br/>Day 1 to Day 35: Normal Mode<br/>Day 36 to Day 44: Warning Banner Displayed
    alt Reconnects before Day 45
        Device->>Server: Sync Data & Verify Lease
        Server-->>Device: Issue Refreshed 45-day Lease Token
    else Day 45 Expires while Offline
        Note over Device: Lease Expiry Triggered:<br/>Lock New Interview Creation<br/>Require Online Check-in
    end
```






### Lease Rules: {#lease-rules}
- The lease token is cryptographically signed by the backend and verified on-device against public keys.
- **Day 1–35**: Seamless offline data collection.
- **Day 36–44**: Amber banner warns enumerator of approaching lease expiration.
- **Day 45+**: New survey submissions are locked. Existing completed records remain encrypted and safely stored until connectivity is restored and online verification completes.
