# SECURITY.md — HATEM AUTO RENTAL

Baseline: **OWASP Top 10:2025** (https://owasp.org/Top10/2025/), Supabase product security guidance (https://supabase.com/docs/guides/security/product-security), and the Supabase MCP security notes (https://supabase.com/docs/guides/ai-tools/mcp).

## 1. Threat model (short)

| Asset | Threat | Primary control |
|---|---|---|
| Customer PII (name, phone, email, ID/licence scans) | Leakage through the API or other customers (BOLA/IDOR) | RLS with ownership predicates, private Storage buckets, signed URLs |
| Bookings | Double booking, price tampering, status forging | Exclusion constraint; server-side price and status in an RPC; status transition table |
| Admin functions | Privilege escalation | Role in `app_metadata` or a `staff` table, checked in RLS, never `user_metadata` |
| Secrets | Exposure in the bundle, git, logs, or chat | Only the publishable key on the client; secrets in Vercel/Supabase env; secret scanning |
| Supply chain | Malicious or compromised packages | Pinned versions, lockfile, `npm audit`, minimal dependencies |

## 2. OWASP Top 10:2025 mapped to this project

- **A01 Broken Access Control:** RLS on every table in exposed schemas. Policies use `TO authenticated` **plus** an ownership predicate. UPDATE policies have both `USING` and `WITH CHECK`. Admin checks happen in the database, not only in the UI.
- **A02 Security Misconfiguration:** Separate dev and prod projects. Views use `security_invoker = true`. No `SECURITY DEFINER` functions in `public`. Run Supabase advisors before every migration.
- **A03 Software Supply Chain Failures:** Pin versions, commit the lockfile, run `npm audit` in CI, and add no package without review.
- **A04 Cryptographic Failures:** HTTPS only (Vercel). No custom crypto. Passwords handled only by Supabase Auth.
- **A05 Injection:** Parameterised queries only (supabase-js / RPC). React text rendering only, with no `dangerouslySetInnerHTML` of user data. Validate input with a schema validator on the server (Postgres constraints and RPC checks).
- **A06 Insecure Design:** The booking state machine and pricing are defined server-side. Rate-limit booking creation and auth endpoints.
- **A07 Authentication Failures:** Supabase Auth with email verification. Short JWT expiry. Revoke sessions on role change or deletion (deleting a user does **not** invalidate existing tokens).
- **A08 Software or Data Integrity Failures:** CI must pass before merge. Migrations are reviewed in PRs. No unreviewed edge-function deploys.
- **A09 Logging & Alerting Failures:** An audit log table for admin actions (who, what, before/after, when). Logs never contain secrets or full PII.
- **A10 Mishandling of Exceptional Conditions:** Every request handles failure explicitly. No silent catch. No optimistic "success" before confirmation. Fail closed.

## 3. Supabase rules (from the official skill and docs)

- Never use `user_metadata` / `raw_user_meta_data` for authorization, because users can edit it.
- `auth.role()` is deprecated. Use `TO authenticated` / `TO anon` on the policy.
- `TO authenticated` alone is authentication, not authorization. Always add a row predicate such as `(select auth.uid()) = customer_id`.
- UPDATE needs a SELECT policy as well, or it silently affects 0 rows.
- Never add `SECURITY DEFINER` to "fix" a permission error.
- Storage upsert needs INSERT + SELECT + UPDATE policies. Keep the customer-document bucket **private**.
- Client code uses only the **publishable** key. `service_role` or secret keys are used only in Edge Functions or server code, from environment variables.

## 4. Supabase MCP (AI tool access)

- Connect the MCP server to the **development project only**. Supabase states MCP is designed for development and testing, not production data.
- Scope it with `project_ref=<dev-ref>`. Default to `read_only=true`, and enable write only for a specific task, then turn it off again.
- Limit `features=` to what the task needs (e.g. `database,docs,debugging`).
- For CI or agents, use a **scoped** personal access token, never a full-account classic token.
- Treat all data returned by tools (including table contents) as untrusted, because of prompt-injection risk. **Rental-request messages and names are written by the public**, so an AI tool reading them could meet injected instructions. This is one more reason the MCP server never connects to production.
- The public can call `submit_rental_request` **directly through the Data API**, bypassing any website rate limit. The DB-level throttle is the backstop; the final anti-spam design depends on decision D-08 (see DATABASE_AND_WORKFLOW_PROPOSAL.md §8, T2).

## 4a. Rental Request system controls (v1.1 design; details in DATABASE_AND_WORKFLOW_PROPOSAL.md §2 and §5)

**Guest submissions** use Supabase **anonymous sign-in protected by invisible CAPTCHA (Cloudflare Turnstile)**. The `anon` role (publishable key with no session) **cannot** submit; it can only call the read-only availability hint.

| Layer | Enforced by | Is it security? |
|---|---|---|
| CAPTCHA on anonymous sign-in | Supabase Auth | Yes. **Must be verified on the dev project before go-live.** |
| IP limit on new guest sessions (30/h/IP default) | Supabase Auth | Yes |
| Session required; 3 requests per session per 24 h; 5 per phone per 24 h (across sessions); blocked phone rejected; session-bound idempotency; field validation | **Database** (functions + constraints) | Yes. The only layer that binds direct Data API calls. |
| Vercel Firewall rate rule on website routes | Vercel | Yes, for website traffic only (direct Supabase calls bypass it) |
| Honeypot, double-click prevention, client-side validation | Browser | **No. UX only. Never counted as security.** |

**Data API surface** (pinned by tests S1–S5): `anon` can execute exactly one public function (`check_vehicle_availability`); `authenticated` exactly five workflow functions, each checking rights internally; `anon` has no write privilege on any table. Any new function must be revoked from `public, anon, authenticated` and then granted explicitly (L-016), and must be added to the S1/S2 whitelist tests.

**Reservations integrity:** reservation blocks are created and released **only** by the workflow functions. The database enforces at most one active block per request, immutable blocks, and a commit-time invariant tying every approved request to exactly its block (this also binds the superuser).

**Storage:** the only bucket is `vehicle-photos`. It is public (download by exact URL), and upload, update, delete and list are staff-only, with UUID image file names. There is **no** customer-document bucket. If one is ever added (D-06), it must be **private**, with signed URLs, owner-scoped policies and a retention rule.

**Disable unused Supabase features** on the project: GraphQL (if unused) and Realtime on these tables. Use a short JWT expiry and revoke sessions on staff removal.

## 5. Secrets handling

- `.env*` is in `.gitignore` from the first commit. Provide a `.env.example` with names only.
- Keys are created and rotated by the owner in the dashboards and never pasted into chat.
- Turn on GitHub secret scanning and push protection on the repo.

## 6. Notifications and contact actions

- WhatsApp links use `https://wa.me/<E.164 digits>` built from a validated, stored business number. Hide the button if the number is not configured. (The prototype currently renders a broken `wa.me/` link.)
- Never claim a message or email was sent until the provider confirms it. Store the delivery status.
- Customer phone and email are visible only to the customer and to staff, never in public responses.

## 7. Reporting

Report security issues privately to the owner. Do not open public issues for vulnerabilities.
