# Enterprise Security Audit - KiyoKart

**Application:** KiyoKart (SaaS E-commerce Platform)  
**Framework:** Laravel 12  
**PHP:** 8.2 (FPM)  
**Stack:** LAMP on Ubuntu 22.04  
**Database:** MySQL 8+  
**Deployment Target:** Production (Public Internet)

---

## Executive Summary

This report consolidates the enterprise-grade security and infrastructure audit for KiyoKart across:

1. Application-level security
2. Laravel framework hardening
3. PHP-FPM hardening
4. Apache hardening
5. MySQL hardening
6. Ubuntu OS hardening
7. Network architecture security
8. SaaS multi-tenant risk model
9. DevOps/CI-CD security
10. Production readiness and go-live controls

Key risk concentrations identified:

- Secrets and sensitive environment data exposure risk
- Unsafe operational utility script in public webroot
- Insecure upload validation path in product creation flow
- Weak default credentials in POS customer creation
- Sensitive request payload logging
- Missing explicit tenant-isolation architecture for SaaS-scale security boundaries

---

## PHASE 1 - Static Code Analysis Findings

### Finding 1 - Secrets exposure risk

- **Risk:** Critical  
- **Files:** `.env`, `config/services.php`
- **Issue:** Sensitive values (app key, payment/SMS secrets, environment settings) were present in local env context and secret fallback defaults exist in config.
- **Impact:** Credential theft, fraud, unauthorized API calls, cryptographic trust compromise.
- **Fix:**
  - Rotate all exposed keys immediately.
  - Move secrets to Vault/KMS/SSM.
  - Enforce secret scanning in CI (`gitleaks`, `trufflehog`).
  - Remove live/default secrets from code/config fallback values.

---

### Finding 2 - Public utility script in webroot

- **Risk:** High  
- **File:** `public/create-storage-link.php`
- **Issue:** Operational script is publicly accessible and can expose server/storage topology.
- **Impact:** Reconnaissance, unintended operational behavior, increased attack surface.
- **Fix:**
  - Remove file from production images.
  - Use `php artisan storage:link` only during deployment.
  - Block access to all operational scripts in Apache config.

---

### Finding 3 - Insecure file upload handling in product create flow

- **Risk:** High  
- **File:** `app/Http/Controllers/Admin/ProductController.php`
- **Issue:** `additional_images` and `videos` were stored without strict validation in create path.
- **Impact:** Malicious file upload, malware staging, potential code execution in misconfigured environments.
- **Fix Applied:**
  - Added validation:
    - `additional_images` array with image MIME constraints
    - `videos` array with explicit video MIME constraints

---

### Finding 4 - Weak default password usage

- **Risk:** High  
- **File:** `app/Http/Controllers/Api/Pos/CustomerController.php`
- **Issue:** Uses `Hash::make('password')` as default for created users.
- **Impact:** Predictable credential abuse and account takeover.
- **Fix:**
  - Replace with random bootstrap password/token.
  - Enforce first-login reset flow.
  - Mark account as `must_reset_password = true`.

---

### Finding 5 - Sensitive payload logging

- **Risk:** High  
- **File:** `app/Http/Controllers/Api/Pos/CustomerController.php`
- **Issue:** Request payload (`$request->all()`) logged in info logs.
- **Impact:** PII leakage, compliance violations, lateral risk via log aggregation.
- **Fix:**
  - Log only minimal metadata (request ID, operation, masked identifiers).
  - Add central PII redaction policy in logging pipeline.

---

### Finding 6 - SQL raw concatenation pattern

- **Risk:** Medium  
- **File:** `app/Http/Controllers/Admin/CategoryController.php`
- **Issue:** `orderByRaw(...)` includes concatenated direction.
- **Impact:** Low current exploitability due guardrails, but fragile against regressions.
- **Fix:**
  - Keep strict whitelist.
  - Avoid user-influenced SQL fragments.
  - Prefer builder-safe ordering strategy when possible.

---

### Finding 7 - Error path null safety gap

- **Risk:** Medium  
- **File:** `app/Http/Controllers/Admin/OrderController.php`
- **Issue:** `decrypt($id)` and `Order::find(...)` used without strict fail handling.
- **Impact:** Exceptions/500 responses, possible info leakage.
- **Fix:**
  - Wrap decrypt in try/catch.
  - Use `findOrFail`.
  - Return consistent 404/403 behavior.

---

### Finding 8 - Mass assignment risk pattern

- **Risk:** Medium  
- **File:** `app/Http/Controllers/Admin/ProductController.php`
- **Issue:** Broad `$request->all()` usage in create/update flows.
- **Impact:** Over-posting risk if model fillables change.
- **Fix:**
  - Replace with explicit `only([...])` allowlists for all write paths.

---

### Finding 9 - Missing throttle on shipping endpoints

- **Risk:** Medium  
- **File:** `routes/web.php`
- **Issue:** Public shipping API routes initially lacked explicit route throttle.
- **Impact:** Scraping, enumeration, abuse pressure.
- **Fix Applied:**  
  - Added `throttle:30,1` to shipping route group.

---

### Finding 10 - SaaS multi-tenant isolation controls absent

- **Risk:** Critical (for SaaS enterprise target)  
- **Issue:** No explicit tenant isolation model detected (`tenant_id`, tenant context enforcement).
- **Impact:** Cross-tenant data leakage and authorization boundary failure risk.
- **Fix Strategy:**
  - Tenant-aware schema and global scopes.
  - Tenant-aware cache/queue/storage partitioning.
  - Mandatory policy checks including tenant boundary.

---

## PHASE 2 - Laravel Production Hardening

### Secure `.env` baseline (template created)

- File created: `.env.production.example`
- Includes hardened defaults:
  - `APP_ENV=production`
  - `APP_DEBUG=false`
  - secure session/cookie flags
  - redis-backed session/cache/queue defaults
  - placeholders for secrets only

### Application hardening controls

- Force HTTPS middleware added
- Security headers middleware added
- Shipping route throttling added
- Upload validation strengthened in product create path

### Recommended additional Laravel controls

- Enforce `URL::forceScheme('https')` in production
- Add strict CSP nonce strategy for scripts
- Use FormRequest classes for all write endpoints
- Add signed URLs for private media delivery
- Introduce centralized authorization policies on all admin mutating actions

---

## PHASE 3 - PHP 8.2 FPM Hardening

### Recommended `php.ini` production settings

```ini
expose_php = Off
display_errors = Off
display_startup_errors = Off
log_errors = On

memory_limit = 256M
max_execution_time = 30
max_input_time = 30
post_max_size = 20M
upload_max_filesize = 10M
max_file_uploads = 10

cgi.fix_pathinfo = 0
allow_url_fopen = Off
allow_url_include = Off

session.use_strict_mode = 1
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Lax

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,show_source
```

### OPcache production block

```ini
opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=50000
opcache.validate_timestamps=0
opcache.revalidate_freq=0
```

### FPM pool baseline

```ini
pm = dynamic
pm.max_children = 60
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12
pm.max_requests = 500
request_terminate_timeout = 60s
security.limit_extensions = .php
```

---

## PHASE 4 - Apache Hardening (Ubuntu 22.04)

### Enable modules

- `ssl`, `headers`, `rewrite`, `http2`, `remoteip`, `socache_shmcb`, `security2`

### Disable modules

- `autoindex`, `status` (public), `info`, `userdir`, and all unused modules

### Core hardening directives

```apache
ServerTokens Prod
ServerSignature Off
TraceEnable Off
Options -Indexes
```

### TLS policy

- Enforce TLS 1.2/1.3 only
- Disable weak ciphers
- Enable HSTS with preload

### WAF and abuse controls

- Deploy ModSecurity + OWASP CRS
- Integrate Fail2Ban for Apache and WAF logs

---

## PHASE 5 - MySQL Hardening

### Recommended controls

- Disable remote root login
- Restrict bind interface to private subnet
- Use least-privilege DB users (app user vs migration user)
- Enable slow query log and monitoring
- Keep strict SQL modes enabled
- Encrypt backups at rest and in transit
- Enable audit logging (native/plugin/SIEM integration)

### `mysqld` baseline excerpts

```ini
local_infile = 0
skip_name_resolve = ON
max_connections = 300
slow_query_log = 1
long_query_time = 0.5
innodb_file_per_table = 1
innodb_flush_log_at_trx_commit = 1
```

---

## PHASE 6 - Ubuntu 22.04 Server Hardening

### UFW baseline

```bash
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

### SSH hardening essentials

- Disable password auth
- Disable root login
- Move SSH to non-default port
- Enforce key-based auth

### Automatic updates

```bash
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
```

### Laravel file ownership/permissions

```bash
sudo chown -R www-data:www-data /var/www/html/kiyokart
sudo find /var/www/html/kiyokart -type f -exec chmod 640 {} \;
sudo find /var/www/html/kiyokart -type d -exec chmod 750 {} \;
sudo chown -R www-data:www-data /var/www/html/kiyokart/storage
sudo chown -R www-data:www-data /var/www/html/kiyokart/bootstrap/cache
sudo chmod -R ug+rwx /var/www/html/kiyokart/storage /var/www/html/kiyokart/bootstrap/cache
sudo chmod 640 /var/www/html/kiyokart/.env
```

---

## PHASE 7 - Network-Level Security

### Recommended production architecture

Internet -> CDN/WAF -> Load Balancer -> Reverse Proxy -> App Tier -> Private Redis/MySQL

### Required controls

- DMZ at edge only
- Private DB subnet with no public exposure
- Network rate limiting at edge and LB
- DDoS protection (provider + WAF)
- DNSSEC + registrar lock + MFA
- Admin panel IP allowlisting and VPN access path

---

## PHASE 8 - SaaS Multi-Tenant Security

### Primary risk themes

- Tenant data isolation gaps
- Cross-tenant leakage via query mistakes
- Non-tenant-aware cache keys
- Shared queues without tenant context
- Shared storage namespace without tenant prefixes

### Enterprise tenant control model

- Add `tenant_id` to all tenant-owned entities
- Apply global tenant scopes
- Add tenant boundary checks in policies
- Prefix cache/queue/storage with tenant context
- Use per-tenant encryption strategy (envelope keys/KMS context)

---

## PHASE 9 - DevOps and CI/CD Security

### Pipeline controls

- Secrets scanning: `gitleaks`
- Dependency audit: `composer audit`
- SAST/semantic rules: `semgrep`
- Artifact integrity and signed release tags
- Protected branches + mandatory code review

### Deployment controls

- Immutable release artifacts
- Zero-downtime deploy (blue/green or rolling)
- Secret injection at runtime from secure manager
- Post-deploy smoke + security checks

---

## PHASE 10 - Final Deliverables

### 1) Risk Matrix

#### Critical

- Secrets exposure risks
- Missing SaaS tenant isolation model

#### High

- Public utility script in webroot
- Insecure upload validation path (now patched)
- Weak default credentials
- Sensitive payload logging

#### Medium

- SQL raw concatenation pattern
- Null-safety/exception handling gaps in encrypted ID flows
- Broad mass-assignment patterns
- Public API throttle coverage gaps (shipping route now patched)

#### Low

- Residual hardening opportunities in CSP strictness and security observability

---

### 2) Immediate Fix Checklist (0-24h)

- Rotate all secrets and invalidate old credentials
- Remove `public/create-storage-link.php` from production
- Remove default passwords from all user creation flows
- Remove sensitive request logging
- Confirm prod env values (`APP_ENV=production`, `APP_DEBUG=false`)
- Validate public route throttle baseline

---

### 3) 7-Day Hardening Plan

**Day 1-2:** Secret rotation + logging cleanup + credential hardening  
**Day 3:** Upload controls + auth flow hardening + route abuse controls  
**Day 4:** Apache/PHP-FPM/MySQL baseline rollout  
**Day 5:** CI security gates and blocking policies  
**Day 6:** Monitoring/SIEM alerts and anomaly detections  
**Day 7:** Focused penetration test on auth/payment/admin paths

---

### 4) 30-Day Enterprise Hardening Plan

- Tenant isolation architecture implementation
- WAF tuning and managed rule governance
- Backup encryption and restore drills
- Compliance mapping to OWASP ASVS, CIS, NIST control families
- Security incident runbooks and tabletop exercises

---

### 5) Production Go-Live Security Checklist

- [ ] No live secrets in repository or artifacts
- [ ] TLS 1.2/1.3 only with HSTS
- [ ] Strict session/cookie security flags enabled
- [ ] WAF + rate limiting + DDoS controls active
- [ ] DB on private subnet with least privilege accounts
- [ ] SSH hardened and OS patching automated
- [ ] Laravel storage/cache permission model validated
- [ ] CI/CD security scans pass with enforced gate policy
- [ ] Backup and rollback tested
- [ ] Tenant isolation controls validated (required for SaaS go-live)

---

## Change Log for This Audit Batch

Implemented in codebase during this security hardening cycle:

- Added `app/Http/Middleware/ForceHttps.php`
- Added `app/Http/Middleware/SecurityHeaders.php`
- Registered middleware in `bootstrap/app.php`
- Added `throttle:30,1` to shipping API route group in `routes/web.php`
- Added strict validation for `additional_images` and `videos` in product create flow
- Added `.env.production.example` hardened template

