# Application Security Architecture & Ghana Compliance

This document details the security controls, authentication safeguards, authorization policies, credential isolation, and legal data protection mechanisms implemented across the Eniceberny platform.

---

## 1. CIA Triad Security Enforcement Matrix

The platform enforces the classic **Confidentiality, Integrity, and Availability (CIA)** triad across all software layers:

| Pillar | Architectural Threat | Enforced Platform Mitigation |
| :--- | :--- | :--- |
| **Confidentiality** | Unauthorized access to patron data or payment credentials | Strict RBAC middleware (`AdminMiddleware`), Bcrypt hashing, automatic audit log redaction, TLS 1.3 HTTPS enforcement. |
| **Integrity** | Tampering with prices, balances, or order records | Server-side price resolution from catalog models, `DB::transaction()` isolation, HMAC webhook verification, CSRF token validation. |
| **Availability** | Denial of Service (DoS) and brute force attacks | Route-level rate limiting (`throttle:6,1`), background queue processing, health check probes (`/up`), automated Docker auto-healing. |

---

## 2. Authentication & Session Security

### 2.1 Password Hashing & Key Derivation
- Passwords are encrypted using standard **Bcrypt** with dynamic cost factors (`Hash::make()`).
- Plaintext passwords are never stored, logged, or serialized.
- On login, hashes are automatically re-evaluated and upgraded if framework work factors increase.

### 2.2 Secure Session Management
- `session.regenerate()` is executed upon successful login and registration to eliminate session fixation vulnerabilities.
- Session cookies are strictly configured with:
  - `HttpOnly`: Prevents client-side JavaScript access via XSS.
  - `SameSite=Lax`: Mitigates Cross-Site Request Forgery (CSRF).
  - `Secure`: Transmitted exclusively over encrypted HTTPS connections in production.

### 2.3 Email OTP Verification Engine
To prevent spam accounts and ensure valid patron communication channels:
- New customer registrations trigger an automated 6-digit cryptographic verification code dispatched via `VerifyEmailOtpMail`.
- **Expiry Window**: OTP tokens expire after 15 minutes.
- **Cooldown Throttling**: A 60-second cooldown is enforced between resend attempts to prevent email flooding.
- **Change Email Feature**: Patrons can correct typographical errors in their email address directly from `/verify-otp` via the **"Change Email Address"** modal.

---

## 3. Role-Based Access Control (RBAC) & Granular Permissions

Access to system capabilities is governed by a hierarchical role model defined in `App\Enums\UserRole`:

```mermaid
graph TD
    SuperAdmin[super_admin: Full System & Financial Access] --> Admin[admin: Operational & Catalog Management]
    Admin --> Manager[manager: Daily Sales, Staff & Inventory]
    Manager --> Cashier[cashier: POS Terminal & Walk-in Orders]
    Manager --> Kitchen[kitchen_staff: Kitchen Queues & Dispatch]
    Customer[customer: Storefront Ordering, Invoices & Addresses]
```

### 3.1 Role Capabilities Matrix

| Role | POS Terminal | Orders & Dispatch | Catalog & Pricing | Settings & Branding | Financial Reports |
| :--- | :---: | :---: | :---: | :---: | :---: |
| **`super_admin`** | Full | Full | Full | Full | Full |
| **`admin`** | Full | Full | Full | Full | Full |
| **`manager`** | Full | Full | Full | Read-Only | Full |
| **`cashier`** | Full | POS Only | Read-Only | None | None |
| **`kitchen_staff`** | None | Update Prep Status | Read-Only | None | None |
| **`customer`** | None | Own Orders Only | Read-Only | None | None |

### 3.2 Granular Permission Overrides
Individual staff accounts support granular capability flags (e.g. `manage_settings`, `manage_users`, `manage_pos`, `view_reports`, `manage_catalog`), allowing fine-grained delegation without elevating full administrative roles.

---

## 4. Ghana Data Protection Act 2012 (Act 843) Compliance

The platform is designed to adhere to the statutory data protection principles mandated by Ghana's **Data Protection Act, 2012 (Act 843)**:

### 4.1 Legal Principles Implemented:
1. **Consent & Purpose Specification (Section 20)**:
   - Patrons explicitly consent to data processing upon account creation.
   - Data collected (Name, Phone Number, Delivery Address) is used exclusively for order fulfillment and customer service.
2. **Data Minimization (Section 21)**:
   - Only data necessary for culinary production and delivery logistics is gathered. No unnecessary biometric or tracking data is requested.
3. **Data Quality & Accuracy (Section 22)**:
   - Patrons can view, edit, and update their profile, telephone numbers, and delivery addresses at any time via `/account`.
4. **Right to Erasure & Rectification (Section 33)**:
   - Customers have the right to request deletion of their account profile. Historical financial orders are anonymized to maintain statutory tax audit records while purging personal identifiers.
5. **Security Safeguards (Section 28)**:
   - Data at rest is encrypted within managed PostgreSQL instances.
   - Communications are encrypted via TLS 1.3.

---

## 5. Automated Sensitive Data Redaction in Audit Logs

The `AuditLog` engine automatically sanitizes all recorded state changes to prevent credential or payment information leakage:

```php
// app/Models/AuditLog.php
protected static array $redactedKeys = [
    'password',
    'password_confirmation',
    'current_password',
    'token',
    'remember_token',
    'secret',
    'api_key',
    'paystack_secret_key',
    'paystack_public_key',
    'card',
    'cvv',
    'pin',
];
```

When an administrator updates settings or user accounts, any matching keys in the request payload are replaced with `[REDACTED]` before saving to the database.

---

## 6. Input Validation & Defense in Depth

- **SQL Injection Prevention**: All queries utilize Eloquent ORM or parameterized bindings (`DB::select('... WHERE id = ?', [$id])`).
- **Cross-Site Scripting (XSS)**: Blade templates enforce automatic HTML entity encoding (`{{ $untrustedInput }}`). Raw unescaped output (`{!! ... !!}`) is strictly prohibited on user-supplied content.
- **CSRF Token Validation**: Every state-altering HTTP request (`POST`, `PUT`, `PATCH`, `DELETE`) requires a verified `@csrf` token or `X-CSRF-TOKEN` header.
- **Rate Limiting**:
  - `throttle:6,1` applied to all authentication, login, and OTP verification endpoints.
  - `throttle:10,1` applied to public contact forms and catering inquiry submissions.
