# Complete Catalog of Defects, Vulnerabilities & Bugs — Nhance Platform

> [!IMPORTANT]
> **Document Purpose:** Detailed technical breakdown and explanation of all **35 confirmed defects, vulnerabilities, and engineering bugs** discovered across the Nhance application codebase.  
> **Target Audience:** Engineering Leadership, Technical Leads, Security Auditors, and Developers implementing remediations.  
> **Source Directory:** All references link to specific files and line numbers in the [`/nhance`](file:///home/aman/Downloads/AmanR/Nhance/nhance/) codebase.

---

## Severity & Domain Distribution

```mermaid
pie title Total 35 Defects by Category
    "Security & Auth (15)" : 15
    "Code Quality & Debt (6)" : 6
    "Database & Integrity (4)" : 4
    "Performance & Scalability (4)" : 4
    "DevOps & CI/CD (4)" : 4
    "UI/UX & Accessibility (2)" : 2
```

---

# 1. Critical & High Security Defects (Immediate Threats)

---

### 1. Account Takeover via Phone Number Update ([`NH-SEC-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-001-unauthenticated-account-takeover-via-mobile-number-update))
* **Severity / Priority:** Critical / P0
* **Location:** [`RestAuthenticationController.php#L2066-L2125`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/RestAuthenticationController.php#L2066-L2125), [`Routes.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Routes.php)
* **What happens:** The endpoint `POST /employeeRest/updateMobileNumber` receives a corporate email (`email_id`) and a new mobile number (`new_mobile_number`). It queries the `employees` table for an active employee record with that corporate email and immediately executes:
  ```php
  $this->employeeModel->update($employeeData['id'], [
      'mobile' => $new_mobile,
  ]);
  ```
* **The bug:** There is **no authentication filter**, no session check, no CSRF token, and no OTP sent to the existing mobile or corporate email to authorize the update.
* **Real-World Consequence:** Any attacker on the internet who knows or guesses any employee's, executive's, or HR administrator's corporate email can overwrite their registered phone number with an attacker-controlled phone number. Once changed, the attacker triggers an OTP login or password reset to completely take over the account.
* **Remediation:** 
  1. Attach the `authJWT` filter to the route in `app/Config/Routes.php`.
  2. Require a multi-factor verification token (OTP delivered to the *current* registered email/mobile) in the payload before committing any phone number change.

---

### 2. Password Overwrite & Plaintext Password Logging ([`NH-SEC-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-002-unauthenticated-password-overwrite--plaintext-password-logging))
* **Severity / Priority:** Critical / P0
* **Location:** [`RestAuthenticationController.php#L1630-L1715`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/RestAuthenticationController.php#L1630-L1715)
* **What happens:** `POST /employeeRest/savePassword` accepts an identifier (`mobile_number` or `email_id`) and a new password (`password`, `confirm_password`), hashes the password with `password_hash()`, and updates the user record in the database.
* **The bugs:** 
  1. The endpoint requires **no old password, no OTP verification, and no active session or bearer token**. Anyone can reset anyone else's password.
  2. At line 1632, the controller executes:  
     `$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - savePassword: Received payload = " . json_encode($this->request->getJSON() ?? []));`  
     This logs the **raw, plaintext password** straight into the system error logs on disk on every submission.
* **Real-World Consequence:** Arbitrary unauthenticated password resets across the entire user base, alongside credential harvesting from log files.
* **Remediation:** Require verified short-lived cryptographic password-reset tokens or active authenticated sessions. Sanitize the request payload before logging to strip password fields.

---

### 3. Complete Authentication Bypass via POS Login ([`NH-SEC-003`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-003-complete-authentication-bypass-via-pos-login-endpoint))
* **Severity / Priority:** Critical / P0
* **Location:** [`LoginController.php#L185-L225`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/LoginController.php#L185-L225), [`Acl.php#L16`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Acl.php#L16)
* **What happens:** The endpoint `POST /getVerifiedPosUserData` receives a mobile number, strips `+91`, queries the `users` table, and if found, executes:
  ```php
  session()->set([
      'user_id'      => $user['id'],
      'user_name'    => $user['first_name'],
      'user_email'   => $user['email'],
      'is_logged_in' => true,
  ]);
  ```
* **The bug:** The route is marked `public => true` in `Acl.php`. The backend assumes the client frontend already completed SMS OTP verification, performing **zero server-side validation**.
* **Real-World Consequence:** Anyone can send a raw POST request with any staff or admin phone number and receive an active, valid administrative web session cookie.
* **Remediation:** Remove this endpoint or enforce server-side validation of a cryptographically signed identity provider token (e.g., Firebase Auth ID token).

---

### 4. Live Cloud Service Account Private Keys Exposed to the Public ([`NH-SEC-004`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-004-live-cloud-credentials--private-keys-exposed-in-web-root))
* **Severity / Priority:** Critical / P0
* **Location:** [`public/oauth-412703-c47b73db19c0.json`](file:///home/aman/Downloads/AmanR/Nhance/nhance/public/oauth-412703-c47b73db19c0.json), [`nhance-ee8d1-e3c5269b1ec7.json`](file:///home/aman/Downloads/AmanR/Nhance/nhance/nhance-ee8d1-e3c5269b1ec7.json), [`app/Config/google-services.json`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/google-services.json)
* **What happens:** Full Google Cloud Service Account credentials (`venkatesh-drive@oauth-412703.iam.gserviceaccount.com` and `firebase-adminsdk...`) containing active RSA 2048-bit private keys are committed into the repository.
* **The bug:** `oauth-412703-c47b73db19c0.json` is stored directly inside `/public/`, making it downloadable by anyone via `https://domain/oauth-412703-c47b73db19c0.json`.
* **Real-World Consequence:** Unauthorized access to corporate Google Drive storage, unauthorized cloud API usage, and the ability to send spoofed push notifications to mobile users.
* **Remediation:** Delete the JSON files immediately from git and `/public/`; revoke the key IDs in Google Cloud Console; move credentials outside the web root and configure paths via environment variables.

---

### 5. Critical PHP Remote Code Execution Vulnerabilities ([`NH-SEC-005`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/05-php-cve-assessment.md))
* **Severity / Priority:** Critical / P0
* **Location:** [`Dockerfile#L1`](file:///home/aman/Downloads/AmanR/Nhance/nhance/Dockerfile#L1), [`bitbucket-pipelines.yml#L6`](file:///home/aman/Downloads/AmanR/Nhance/nhance/bitbucket-pipelines.yml#L6), Local Host Runtime
* **What happens:** On October 21, 2026, the PHP Project released security advisories for **CVE-2026-109618** (OOM Memory Corruption) and **CVE-2026-109619** (Use-After-Free via Stale Global State) with a **CVSS score of 9.2 (Critical)**.
* **The bug:** Nhance's `Dockerfile` uses `FROM php:8.3-apache` (Apache `mod_php`), and the local runtime is `PHP 8.3.6`. In Apache `mod_php`, worker processes handle multiple sequential requests, matching the exact conditions required for remote unauthenticated memory corruption and code execution.
* **Real-World Consequence:** Remote Code Execution on the web server without requiring credentials.
* **Remediation:** Rebuild all containers using patched base images (`php:8.3.36-apache` or `php:8.4.27-apache`) and upgrade host operating system packages.

---

### 6. Global CSRF Protection Disabled ([`NH-SEC-006`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-006-global-csrf-protection-disabled-across-entire-application))
* **Severity / Priority:** High / P1
* **Location:** [`Filters.php#L79`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Filters.php#L79), [`Security.php#L108`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Security.php#L108)
* **What happens:** In `app/Config/Filters.php`, the global CSRF filter is commented out:
  ```php
  // 'csrf',
  ```
* **The bug:** No incoming state-changing request (POST, PUT, DELETE) is checked for a valid CSRF token.
* **Real-World Consequence:** Any authenticated user visiting a malicious external website can have unintended actions performed on their behalf (e.g., submitting claims, approving endorsements, altering user privileges).
* **Remediation:** Uncomment `'csrf'` in `Filters.php` and exempt only stateless API routes (`api/*`, `employeeRest/*`).

---

### 7. Unauthenticated Mass Download of Medical Claims & Documents ([`NH-SEC-007`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-007-unauthenticated-mass-exfiltration-of-employee-claims--medical-records))
* **Severity / Priority:** Critical / P0
* **Location:** [`TicketController.php#L2597-L2620`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/TicketController.php#L2597-L2620), [`StorageFilesController.php#L170`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/StorageFilesController.php#L170), [`Acl.php#L24`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Acl.php#L24)
* **What happens:** `downloadClaimFile($claim_file_id)` streams claim documents by sequential integer ID. `forceDownloadByFolderFile()` streams any file from `writable/uploads/`.
* **The bug:** Both endpoints are marked `public => true` in `Acl.php` and have zero authentication or authorization checks.
* **Real-World Consequence:** An external script can enumerate `id=1` to `id=500000` to dump all confidential hospital discharge summaries, diagnostic reports, and medical bills.
* **Remediation:** Require authenticated sessions and verify that the requesting user's organization owns the requested claim document.

---

### 8. Public Unauthenticated Mass Download of Full Employee Rosters ([`NH-SEC-008`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-008-public-unauthenticated-mass-download-of-full-employee-roster--pii))
* **Severity / Priority:** Critical / P0
* **Location:** [`EmployeeRestController.php#L739-L780`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeRestController.php#L739-L780), [`Acl.php#L105`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Acl.php#L105)
* **What happens:** `GET /employeeRest/downloadEmployeeListExcel?client_id=1&policy_id=1&branch_id=1` builds and returns an Excel spreadsheet containing employee codes, names, dates of birth, genders, mobile numbers, corporate emails, and TPA IDs.
* **The bug:** The route has no `authJWT` filter, and `/employeeRest` is marked public in `Acl.php`.
* **Real-World Consequence:** Unrestricted bulk exfiltration of employee directories and PII across corporate clients.
* **Remediation:** Apply `authJWT` to the route and verify the user has administrative privileges for the requested `client_id`.

---

### 9. Cross-Tenant Broken Object Level Authorization (BOLA) in Non-EB API ([`NH-SEC-009`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-009-cross-tenant-broken-object-level-authorization-bola-in-non-eb-api))
* **Severity / Priority:** High / P1
* **Location:** [`NonEbClaimApiController.php#L454-L520, L710-L760`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/Api/NonEbClaimApiController.php#L454-L520)
* **What happens:** In `claimHistory(claim_id)` and `uploadRequiredDoc_v1(claim_id)`, the controller fetches claim details solely using the URL `claim_id`.
* **The bug:** The code **never verifies that the claim's `client_id` matches the authenticated user's `client_id`**.
* **Real-World Consequence:** An authenticated user from Company A can view loss estimates, surveyor remarks, and settlement amounts for Company B, or upload arbitrary documents to Company B's claim.
* **Remediation:** Enforce tenant ownership predicates: `WHERE id = ? AND client_id = ?`.

---

### 10. Hardcoded Remote Production Database Credentials in Repository ([`NH-SEC-010`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-010-hardcoded-remote-production-database-credentials-in-repository))
* **Severity / Priority:** High / P0
* **Location:** [`Database.php#L55-L75`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Database.php#L55-L75)
* **What happens:** The `$tests` database connection group hardcodes:
  - Host: `119.18.54.85`
  - User: `venbaehn_nhance_user1`
  - Password: `[LIVE_PASSWORD_REDACTED]`
  - Port: `3306`
* **Real-World Consequence:** Direct remote TCP access to the live MySQL database for anyone with source code access.
* **Remediation:** Rotate the database password immediately; load credentials dynamically from `.env`.

---

### 11. Stored Cross-Site Scripting (XSS) via Unescaped View Variables ([`NH-SEC-011`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-011-stored-cross-site-scripting-xss-via-unescaped-view-variables))
* **Severity / Priority:** High / P1
* **Location:** [`thz_notes.php#L138-L235`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Views/thz_notes.php#L138-L235), [`policies.php#L42`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Views/policies.php#L42)
* **What happens:** Views output database values directly using raw `<?= $master[0]['subject']; ?>` without calling `esc()`.
* **The bug:** The input filter ([`SecurityInputFilter.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Filters/SecurityInputFilter.php)) uses an easily bypassed regex blocklist and ignores JSON bodies.
* **Real-World Consequence:** Stored XSS executes malicious JavaScript in administrators' browsers when viewing support tickets.
* **Remediation:** Wrap all view variables in CodeIgniter's `esc()` helper.

---

### 12. Web Root Misconfiguration Exposing System Directories and Git ([`NH-SEC-012`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-012-web-root-misconfiguration-exposing-system-directories-and-git))
* **Severity / Priority:** High / P1
* **Location:** [`.htaccess#L28`](file:///home/aman/Downloads/AmanR/Nhance/nhance/.htaccess#L28), [`Dockerfile#L17`](file:///home/aman/Downloads/AmanR/Nhance/nhance/Dockerfile#L17)
* **What happens:** Apache DocumentRoot is pointed to the repository root. The root `.htaccess` only rewrites requests to `public/` if the file *does not exist* (`RewriteCond %{REQUEST_FILENAME} !-f`).
* **The bug:** Files physically present in the root (`composer.json`, `Dockerfile`, `bitbucket-pipelines.yml`, `.env.sample`, `ca.pem`) are served directly as static files.
* **Real-World Consequence:** Direct disclosure of source code, configuration, and infrastructure manifests over HTTP.
* **Remediation:** Configure Apache DocumentRoot strictly to `/var/www/html/public`.

---

### 13. Hardcoded Google Gemini AI API Keys in Source Files ([`NH-SEC-013`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-013-hardcoded-google-gemini-ai-api-keys-in-source-files))
* **Severity / Priority:** Medium / P1
* **Location:** [`HrAnalyticsGeminiService.php#L66`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Services/HrAnalyticsGeminiService.php#L66), [`Home.php#L44-L70`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/Home.php#L44-L70)
* **What happens:** If `GEMINI_API_KEY` is not set in `.env`, the code falls back to a hardcoded string: `'AIzaSyBbx-uotRBqkYhqLpmD60420E_a0G0duP8'`.
* **Real-World Consequence:** Quota theft and unauthorized API usage billed to the company's Google Cloud account.
* **Remediation:** Revoke the key in Google Cloud Console; fail closed if `env('GEMINI_API_KEY')` is missing.

---

### 14. Mobile Number User Enumeration ([`NH-SEC-014`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-014-unauthenticated-mobile-number-user-enumeration))
* **Severity / Priority:** Medium / P1
* **Location:** [`LoginController.php#L150-L184`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/LoginController.php#L150-L184)
* **What happens:** `POST /getVerifyPosMobileNo` takes a mobile number and returns the complete user database row.
* **Real-World Consequence:** Allows automated scraping of user rosters for spear-phishing campaigns.
* **Remediation:** Return only a generic boolean status without user details.

---

### 15. Arbitrary Employee Deletion via GET Request ([`NH-SEC-015`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/04-security-audit.md#finding-nh-sec-015-arbitrary-dependentemployee-deletion-via-get-request))
* **Severity / Priority:** High / P1
* **Location:** [`EmployeeRestController.php#L549-L570`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeRestController.php#L549-L570)
* **What happens:** `GET /employeeRest/deleteDependence?id=123` executes `UPDATE employees SET is_active = 0 WHERE id = ?`.
* **The bug:** Destructive deletion performed via an unauthenticated GET request without ownership checks.
* **Real-World Consequence:** Anyone can soft-delete any employee or dependent by guessing an ID.
* **Remediation:** Change to `POST`/`DELETE`, add `authJWT`, and verify ownership.

---

# 2. Database & Data Integrity Bugs

---

### 16. Missing Transactions on Multi-Table Writes ([`NH-DB-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/06-database-and-data-integrity.md#finding-nh-db-001-lack-of-database-transactions-leading-to-inconsistentorphan-records))
* **Severity / Priority:** High / P1
* **Location:** Master Controllers & Models; [`RecreateOrphanDumpTickets.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Commands/RecreateOrphanDumpTickets.php#L1)
* **What happens:** Complex operations (policy inception, dependent enrollment, claim dumps) execute multiple sequential `INSERT`/`UPDATE` statements without `$db->transStart()`.
* **The bug:** If query 3 fails after queries 1 and 2 succeed, the previous rows are **never rolled back**.
* **Real-World Consequence:** Orphaned and corrupted database records. The problem is so frequent that developers had to create a dedicated CLI command, `RecreateOrphanDumpTickets`, just to clean up orphan dump records.
* **Remediation:** Wrap all multi-table mutations in `$db->transStart()` ... `$db->transComplete()`.

---

### 17. Flawed Background Job Row Locking Outside Transactions ([`NH-DB-004`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/06-database-and-data-integrity.md#finding-nh-db-004-flawed-background-job-row-locking-outside-transactions))
* **Severity / Priority:** High / P1
* **Location:** [`JobWorker.php#L360-L380`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/JobWorker.php#L360-L380)
* **What happens:** The queue worker executes:  
  `SELECT id, name, payload, uuid FROM jobs WHERE status='queued' LIMIT 1 FOR UPDATE`
* **The bug:** In MySQL/InnoDB, `FOR UPDATE` only holds a lock **inside an active transaction**. Without `transBegin()`, the lock is released the instant the query finishes.
* **Real-World Consequence:** Race conditions. Two worker daemons running in parallel poll the same job, execute it twice, and cause duplicate emails, duplicate claims, or double processing.
* **Remediation:** Wrap the query and status update in `$db->transBegin()` ... `$db->transCommit()`.

---

### 18. Disabled Database Strict Mode & Inadequate 3-Byte UTF-8 ([`NH-DB-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/06-database-and-data-integrity.md#finding-nh-db-002-missing-database-strict-mode-and-3-byte-utf-8-utf8mb3-configuration))
* **Severity / Priority:** Medium / P2
* **Location:** [`Database.php#L42-L45`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Database.php#L42-L45)
* **What happens:** Database configuration sets `'charset' => 'utf8'` and `'strictOn' => false`.
* **The bug:** 
  1. MySQL `utf8` is only 3-byte (`utf8mb3`). 4-byte Unicode characters (emojis, mathematical symbols) cause silent string truncation or query errors.
  2. With strict mode off, MySQL allows invalid dates (`0000-00-00`) and silent string truncation.
* **Remediation:** Upgrade charset to `utf8mb4` with collation `utf8mb4_unicode_ci` and enable `strictOn => true`.

---

### 19. Suppressed Foreign Key Constraints Due to Schema Mismatches ([`NH-DB-003`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/06-database-and-data-integrity.md#finding-nh-db-003-suppressed-foreign-key-constraints-and-column-type-inconsistencies))
* **Severity / Priority:** Medium / P2
* **Location:** [`csat_client_touchpoints_no_fk.sql#L1-L15`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Database/csat_client_touchpoints_no_fk.sql#L1-L15)
* **What happens:** Developer comments in SQL files note:  
  `-- Same table WITHOUT foreign keys — use when legacy clients/csat_touchpoints block FK creation (signed/unsigned mismatch, MyISAM, missing parent table, etc.).`
* **The bug:** Primary and foreign keys mix signed and unsigned integers (`INT` vs `INT UNSIGNED`), preventing foreign key creation.
* **Real-World Consequence:** The database engine cannot enforce relational integrity, allowing orphaned child records when parent rows are deleted.
* **Remediation:** Standardize all ID columns to `INT UNSIGNED NOT NULL` and re-enable foreign keys.

---

# 3. Performance & Scalability Bottlenecks

---

### 20. Synchronous 10-Slide PDF Generation Denial of Service ([`NH-PERF-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/03-performance-and-efficiency.md#finding-nh-perf-001-unbounded-in-memory-multi-slide-pdf-generation-causing-denial-of-service))
* **Severity / Priority:** High / P1
* **Location:** [`HrAnalyticsReportPdfService.php#L20-L65`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Libraries/HrAnalyticsReportPdfService.php#L20-L65), [`Filters.php#L68`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Filters.php#L68)
* **What happens:** To generate the 10-slide HR presentation PDF, the code sets `memory_limit 512M` and `set_time_limit 300`, boots up **10 separate Dompdf instances in a loop**, writes 10 intermediate PDFs to disk, and merges them using `Mpdf\Mpdf`—all synchronously in an HTTP web request.
* **The bug:** The endpoint is exempted from `AclFilter`.
* **Real-World Consequence:** Ten concurrent requests demand 5 GB of RAM and lock 10 web worker processes for up to 5 minutes, crashing Apache with Out-Of-Memory errors.
* **Remediation:** Offload PDF generation to a background queue; return HTTP 202 Accepted with a polling status token.

---

### 21. Widespread N+1 Query Loops on Roster & Premium Updates ([`NH-PERF-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/03-performance-and-efficiency.md#finding-nh-perf-002-widespread-n1-query-loops-across-roster-and-policy-updates))
* **Severity / Priority:** High / P1
* **Location:** [`EmployeeRestController.php#L393-L425`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeRestController.php#L393-L425) (104 loop query sites found across controllers)
* **What happens:** In `updatePremiumAmount`, the code iterates over every employee and dependent, running a separate `SELECT` query followed by a separate `UPDATE` query per row.
* **Real-World Consequence:** A corporate client with 1,500 employees and 3,500 dependents triggers **over 7,000 discrete SQL queries sequentially**, causing browser timeouts and database CPU spikes.
* **Remediation:** Replace loop queries with bulk operations (`updateBatch()` / `INSERT ... ON DUPLICATE KEY UPDATE`).

---

### 22. File-Based Caching for Rate Limiting Impeding Clustering ([`NH-PERF-003`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/03-performance-and-efficiency.md#finding-nh-perf-003-file-based-cache-for-rate-limiting-impeding-horizontal-scalability))
* **Severity / Priority:** Medium / P2
* **Location:** [`Cache.php#L26`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Config/Cache.php#L26), [`RateLimiterService.php#L35`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Libraries/RateLimiterService.php#L35)
* **What happens:** The application uses `file` cache (`WRITEPATH . 'cache/'`) for all rate-limiting counters.
* **Real-World Consequence:**
  1. Disk I/O lock contention on every incoming request.
  2. In a multi-server setup behind a load balancer, each server maintains its own isolated counter. An attacker can distribute requests across nodes to bypass rate limits entirely.
* **Remediation:** Switch the cache driver to Redis.

---

### 23. Missing cURL Timeouts in Third-Party API Helper ([`NH-PERF-004`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/03-performance-and-efficiency.md#finding-nh-perf-004-missing-curl-connection-and-execution-timeouts-in-third-party-api-helper))
* **Severity / Priority:** Medium / P1
* **Location:** [`api_helper.php#L6-L50`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Helpers/api_helper.php#L6-L50)
* **What happens:** `call_third_party_api()` sets up cURL options but sets neither `CURLOPT_CONNECTTIMEOUT` nor `CURLOPT_TIMEOUT`.
* **Real-World Consequence:** If an external partner API (TPA, SMS gateway, insurer) hangs, the PHP worker thread freezes indefinitely until global web server timeout, leading to thread pool exhaustion.
* **Remediation:** Enforce default connection (5s) and execution (20s) timeouts on all cURL requests.

---

# 4. Code Quality & Architectural Defects

---

### 24. Massive Monolithic "God Controllers" ([`NH-CQ-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/02-code-quality.md#finding-nh-cq-001-extreme-god-controllers-violating-single-responsibility-principle))
* **Severity / Priority:** Medium / P2
* **Location:** [`ClientController.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/ClientController.php) (11,045 lines), [`EmployeeRestController.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeRestController.php) (10,996 lines), [`PolicyTransactionController.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/PolicyTransactionController.php) (9,415 lines), [`EmployeeController.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeController.php) (9,339 lines), [`LeadsController.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/LeadsController.php) (9,236 lines).
* **The bug:** 7 controllers contain over 62,000 lines of code. Individual controllers handle parameter parsing, raw SQL building, mathematical calculations, email formatting, file uploads, and HTML rendering all at once.
* **Real-World Consequence:** High cyclomatic complexity, frequent merge conflicts, and near impossibility of writing unit tests.
* **Remediation:** Decompose controllers into single-responsibility domain services (e.g. `ClientKycService`, `RosterService`).

---

### 25. Active Debug Statements (`die()`, `print_r()`) Left in Production ([`NH-CQ-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/02-code-quality.md#finding-nh-cq-002-active-debug-statements-die-print_r-left-in-production-controllers))
* **Severity / Priority:** High / P1
* **Location:** [`DeployController.php#L127, L137, L217`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/DeployController.php#L127-L218)
* **What happens:** Production methods contain active debug halts:
  - Line 127: `echo 'HI';die();`
  - Line 137: `echo 'cool';die();`
  - Line 217: `print_r($cmd);die();`
* **Real-World Consequence:** Calling these features terminates execution unexpectedly with raw debug strings.
* **Remediation:** Remove debug statements and add CI lint rules that reject `die()` / `var_dump()` in PRs.

---

### 26. Hardcoded Local Developer Windows File Paths ([`NH-CQ-003`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/02-code-quality.md#finding-nh-cq-003-hardcoded-local-developer-windows-file-paths-in-production-logic))
* **Severity / Priority:** Low / P3
* **Location:** [`Home.php#L107-L113`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/Home.php#L107-L113)
* **What happens:** Core code references local Windows workstation paths:  
  `$filePath = 'C:\Users\Venba\Desktop\ins stmts\NIC MDU June-2025 (1).pdf';`
* **Real-World Consequence:** Crashes with `FileNotFoundException` on Linux servers.
* **Remediation:** Parameterize paths or remove experimental test methods.

---

### 27. Framework Core Committed In-Tree Instead of Package-Managed ([`NH-CQ-004`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/02-code-quality.md#finding-nh-cq-004-in-tree-framework-forking-and-outdated-framework-version))
* **Severity / Priority:** Medium / P2
* **Location:** [`system/CodeIgniter.php#L57`](file:///home/aman/Downloads/AmanR/Nhance/nhance/system/CodeIgniter.php#L57), [`composer.json#L2`](file:///home/aman/Downloads/AmanR/Nhance/nhance/composer.json#L2)
* **What happens:** CodeIgniter v4.4.5 core framework files are committed directly into git under `/system` rather than being managed as a Composer dependency.
* **Real-World Consequence:** Framework security patches cannot be applied cleanly via `composer update`.
* **Remediation:** Migrate to `codeigniter4/framework` managed via Composer; remove `/system` from git.

---

### 28. Detailed Stack Traces and Server Paths Leaked in Error Responses ([`NH-CQ-005`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/02-code-quality.md#finding-nh-cq-005-detailed-stack-traces-and-internal-server-paths-leaked-in-error-responses))
* **Severity / Priority:** Medium / P2
* **Location:** [`RestAuthenticationController.php#L1715-L1725`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/RestAuthenticationController.php#L1715-L1725), [`EmployeeRestController.php#L185`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Controllers/EmployeeRestController.php#L185)
* **What happens:** Exception handlers catch `\Throwable` and return full internal server paths, file names, line numbers, function names, and stack traces in the HTTP 500 JSON response.
* **Real-World Consequence:** Information disclosure that aids attackers in fingerprinting the application.
* **Remediation:** Log exceptions internally with a UUID request ID; return only a generic error message and the request ID to the client.

---

### 29. Code Duplication & Legacy File Proliferation
* **Severity / Priority:** Low / P3
* **Location:** Throughout repository (e.g. `ThzController_old.php`, `TPADataCompareHelper2.php`, `GlobalPostFileUploadGuard_OLD.php`, `hr_analytics_report_dashboard_old_1.php`, `header_old.php`).
* **The bug:** When developers revise a feature, they create a new copy and leave the old version in the active codebase with `_old` or `2` suffixes.
* **Real-World Consequence:** Confusion over which class is canonical; risk of unmaintained legacy files being called via alternate routes.
* **Remediation:** Delete all `*_old.php` files; rely on git history for archival.

---

# 5. DevOps, CI/CD & Infrastructure Defects

---

### 30. Missing `composer.lock` & Wildcard Package Constraints ([`NH-OPS-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/09-testing-devops-and-observability.md#finding-nh-ops-001-missing-composerlock-and-unpinned-dependency-constraints))
* **Severity / Priority:** High / P1
* **Location:** [`composer.json#L28`](file:///home/aman/Downloads/AmanR/Nhance/nhance/composer.json#L28), repository root
* **What happens:** No `composer.lock` exists in the repository, and line 28 specifies `"mpdf/mpdf": "*"`.
* **Real-World Consequence:** Deployments are non-deterministic. Every `composer install` fetches floating package versions, risking sudden production breakage or supply chain compromise.
* **Remediation:** Pin all dependency versions, run `composer update` in staging, and commit `composer.lock`.

---

### 31. Insecure Cleartext FTP Deployment in CI/CD Pipeline ([`NH-OPS-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/09-testing-devops-and-observability.md#finding-nh-ops-002-insecure-cleartext-ftp-deployment-without-ci-testing))
* **Severity / Priority:** High / P1
* **Location:** [`bitbucket-pipelines.yml#L15-L18`](file:///home/aman/Downloads/AmanR/Nhance/nhance/bitbucket-pipelines.yml#L15-L18)
* **What happens:** The pipeline deploys directly via `git ftp push -u $FTP_USERNAME -p $FTP_PASSWORD $FTP_URL`.
* **The bug:** Plain FTP transmits credentials and source code unencrypted. The pipeline contains zero automated test or linting steps.
* **Real-World Consequence:** Insecure credential transport; broken code deploys directly to production on git push.
* **Remediation:** Replace Git-FTP with SSH/SFTP or container deployment; add mandatory test stages.

---

### 32. Inability to Execute Automated Test Suite Locally ([`NH-OPS-003`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/09-testing-devops-and-observability.md#11-inability-to-execute-test-suites-confirmed-defect))
* **Severity / Priority:** Medium / P2
* **Location:** [`phpunit.xml.dist`](file:///home/aman/Downloads/AmanR/Nhance/nhance/phpunit.xml.dist#L1), `vendor/bin/phpunit`
* **What happens:** `vendor/` is missing, `composer.lock` is missing, and running tests fails immediately. Furthermore, the test database configuration in `Database.php` points to an external remote IP instead of a local ephemeral test database.
* **Real-World Consequence:** Developers cannot verify whether code changes break existing functionality before committing.
* **Remediation:** Establish a working local test environment with SQLite / local MySQL and commit `composer.lock`.

---

### 33. Dockerfile Exposes Entire Repository to Web Server ([`NH-OPS-004`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/09-testing-devops-and-observability.md#finding-nh-ops-004-container-image-exposing-entire-source-code-to-web-server))
* **Severity / Priority:** High / P1
* **Location:** [`Dockerfile#L15-L21`](file:///home/aman/Downloads/AmanR/Nhance/nhance/Dockerfile#L15-L21)
* **What happens:** `COPY . /var/www/html` copies the whole repository (including `app/`, `system/`, `.git/`, and tests) into the Apache web root.
* **Real-World Consequence:** If `.htaccess` is bypassed or misconfigured, all source code and internal config files are readable over HTTP.
* **Remediation:** Add a `.dockerignore` file and set Apache DocumentRoot strictly to `/var/www/html/public`.

---

# 6. UI/UX & Accessibility Defects

---

### 34. Dual Light & Dark Mode Stylesheets Loaded Simultaneously ([`NH-UI-001`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/07-ui-ux-and-accessibility.md#finding-nh-ui-001-dual-light-and-dark-mode-render-blocking-stylesheets))
* **Severity / Priority:** Low / P3
* **Location:** [`header.php#L33-L40`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Views/layout/header.php#L33-L40)
* **What happens:** Every page loads both `bootstrap-creative.min.css` and `bootstrap-creative-dark.min.css` in `<head>`.
* **Real-World Consequence:** Doubles render-blocking CSS payload (~600KB), degrades First Contentful Paint (FCP), and causes layout reflows.
* **Remediation:** Conditionally load only the user's active theme stylesheet.

---

### 35. Missing Accessible Labels & Contrast Failures (WCAG 2.2 AA) ([`NH-UI-002`](file:///home/aman/Downloads/AmanR/Nhance/nhance/audit/07-ui-ux-and-accessibility.md#finding-nh-ui-002-missing-semantic-html-and-accessible-labels-in-critical-forms))
* **Severity / Priority:** Medium / P3
* **Location:** [`policies.php#L40-L45`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Views/policies.php#L40-L45), [`login.php`](file:///home/aman/Downloads/AmanR/Nhance/nhance/app/Views/login.php)
* **What happens:** Form inputs omit `<label for="...">` pairings, icon-only buttons (`mdi mdi-download`, `mdi-delete`) have no `aria-label`, and focus outline is reset to `outline: none` without replacement.
* **Real-World Consequence:** Screen readers cannot announce input names; keyboard-only users cannot see where focus is located. Fails WCAG 2.2 AA compliance.
* **Remediation:** Pair all inputs with `<label for="...">`, add `aria-label` to icon links, and implement high-contrast `:focus-visible` styling.

