# Row-level data privacy

> Ensure every customer sees only their own rows. Enforce ownership checks on the server, handle staff exceptions safely, and verify with two accounts.

- Canonical: https://exaspark.ai/docs/row-level-data-privacy/

## What row-level data privacy actually means

Sign-in proves *who* is visiting, and roles prove *what tier* they hold (Member, Staff, or Admin). Neither stops Customer A from opening Customer B's invoice, booking, or intake form.

**Row-level data privacy** closes that gap. Before returning, editing, or deleting any record, your server verifies the signed-in caller owns that specific row — or holds an explicit staff, workspace, or admin exception.

Every production table should default to **deny**:

- **No rule means no access.** Unless an endpoint proves the caller may see a row, the server returns zero bytes.
- **Browser filtering is cosmetic.** Hiding other customers' rows in UI code still leaks their JSON in browser DevTools.
- **Session identity is authoritative.** Always read `session.user.id` from the verified HTTP-only session cookie — never from a client-supplied `user_id`.

## The four row-access models every app uses

Almost every table in a real business app fits cleanly into one of four row-access models. Naming the exact model per table when prompting ExaSpark eliminates ambiguous rules across routes.

| Access model | Who can read rows | Who can create or edit rows | Typical tables |
| --- | --- | --- | --- |
| **Public read, Admin write** | Anyone (strictly published rows and public columns only) | Admin only | `products`, `classes`, `blog_posts`, `public_reviews` |
| **Owner-only (Personal scope)** | Only the user where `row.user_id === session.user.id` | Signed-in user (server stamps `user_id = session.user.id`) | `bookings`, `orders`, `saved_addresses`, `invoices`, `profiles` |
| **Workspace / Team scope** | Active members of `row.workspace_id` verified via `workspace_members` | Workspace members with permitted workspace role (`admin`, `editor`, `member`) | `projects`, `tasks`, `client_files`, `team_notes` |
| **Role-elevated exception** | Row owner, plus assigned Staff or global Admin | Owner (within allowed states/fields) or Admin | `appointments`, `support_tickets`, `subscriptions`, `payouts` |

### Why column projection matters alongside row privacy

Even when a row is legitimately public — such as a product review or community profile — not every **column** on that row or its linked `users` record should be public.

Always select explicit safe columns (`display_name`, `avatar_url`, `rating`, `comment`) on public queries so sensitive columns like `email`, `phone`, `home_address`, `stripe_customer_id`, or `internal_staff_notes` never leak in API responses.

## How server-enforced rules work on every operation

Row-level privacy is not a single toggle — it must hold consistently across all five operations (`LIST`, `READ ONE`, `CREATE`, `UPDATE`, `DELETE`) plus exports and private file downloads. Missing even one route creates a hole.

```text
TABLE: bookings (user_id, service_id, starts_at, status, price_cents, staff_notes)

OPERATION      SERVER POLICY RULE
-------------------------------------------------------------------------------------
LIST           If role == 'admin': allow all (paginated)
               If role == 'staff': filter WHERE assigned_staff_id = session.user.id
               If role == 'member': filter WHERE user_id = session.user.id

READ ONE       Fetch booking by :id; require owner OR assigned staff OR admin.
               Return 404 Not Found if unauthorized so callers cannot probe valid IDs.
               Strip `staff_notes` unless role IN ('staff', 'admin').

CREATE         Require signed-in user. Ignore any `user_id` or `price_cents` from body.
               Stamp user_id = session.user.id and compute price_cents from `services`.

UPDATE         Require owner OR admin. Whitelist editable fields by role:
               Member may only edit `customer_notes` or cancel >24h before `starts_at`.
               Never let Member overwrite `user_id`, `price_cents`, `status = 'paid'`,
               or `staff_notes`.

DELETE         Admin only (prefer setting status = 'canceled' or archived_at).
```

Notice two subtle production details in that blueprint:

- **Returning `404` on unauthorized single-row reads.** Returning `403 Forbidden` confirms that a guessed record ID exists, whereas returning `404 Not Found` gives an attacker zero information about other customers' IDs.
- **Field whitelisting on writes.** Checking row ownership prevents User A from editing User B's order, while whitelisting editable fields prevents User A from marking their *own* unpaid order as `status = "paid"` or setting `price_cents = 0`.

## Five real-world leakage mistakes (and how to stop them)

When security audits uncover data leaks in newly launched apps, the cause is almost always one of these five patterns.

- **Securing the list endpoint, forgetting the detail endpoint (IDOR).** `/api/bookings` filters by `session.user.id`, yet `/api/bookings/:id` fetches strictly by `:id`. Anyone who swaps an ID in the URL reads another customer's appointment.
- **Trusting a client-supplied `workspace_id` or `user_id`.** Reading `GET /api/projects?workspace_id=ws_other` without checking `workspace_members` for `(ws_other, session.user.id)` exposes another company's projects immediately.
- **Unprotected CSV exports or PDF invoice links.** Securing `/account/invoices` in the app while leaving `/api/invoices/:id/pdf` checking only "is the user signed in?" lets any member download another buyer's receipt.
- **Over-broad Staff or Admin exceptions.** Granting Staff full access to billing settings, password logs, or unrelated locations instead of scoping Staff strictly to assigned rosters or queues widens the blast radius of any compromised staff login.
- **Stale access after removing a teammate.** Deleting a user from `workspace_members` must block their access on the very next API request. Always check live membership rows on the server instead of caching permanent workspace lists inside long-lived tokens.

## Testing row isolation with two Preview accounts

Never assume privacy rules work just because the happy path looks right. Use **Preview** — whose database and user accounts are completely isolated from Live — to run a five-minute adversarial check with two separate accounts.

1. **Create three accounts in Preview** — Register `alice@example.com` (Member), `bob@example.com` (Member), and one Admin account promoted in **Cloud → Preview**.
2. **Generate private records as Alice** — Sign in as Alice and create a booking, upload a private attachment, and open the booking detail URL. Copy the exact record ID and detail URL.
3. **Attack Alice's URLs while signed in as Bob** — Open an incognito window, sign in as Bob, and paste Alice's detail URL, PDF receipt URL, and edit/cancel routes directly into the address bar or DevTools console.
4. **Verify strict server rejection and zero leaks** — Confirm Bob receives `404` or `403`, never sees Alice's name, email, or notes in Network responses, and cannot modify Alice's record.
5. **Confirm Staff and Admin exceptions explicitly** — Sign in as Admin (and Staff if used), confirm they see strictly their authorized scope, and confirm Member accounts remain blocked from `/admin` endpoints.

> **Example prompt (App):** Audit and enforce strict server-side row-level data privacy across every API route and database query. Use default-deny rules: Members may only list, view, or update records where `user_id === session.user.id` (returning 404 on unauthorized detail lookups), while workspace routes must verify active membership in `workspace_members` on every request. Never accept `user_id`, `role`, or `price_cents` from client payloads, whitelist editable fields on every PATCH route, strip private fields like `email`, `phone`, and `staff_notes` from public or non-staff responses, and apply the same ownership checks to private file download and PDF receipt routes.

## Row privacy troubleshooting table

Use this diagnosis table if testing reveals either an unintended leak or an overly strict rule blocking legitimate users.

| Symptom | Root cause | Fix |
| --- | --- | --- |
| **Bob can view Alice's booking by pasting her URL** | Detail route `GET /api/bookings/:id` lacked `AND user_id = session.user.id` (IDOR) | Enforce ownership or Staff/Admin check on every `:id` route and return `404` on mismatch |
| **Admin dashboard went blank after tightening ownership rules** | Query filtered unconditionally by `user_id = session.user.id` without an admin branch | Add explicit server-side role exception (`role === 'admin'`) only on verified admin routes |
| **Public reviews page exposes customer email addresses** | Endpoint returned `SELECT *` from joined `users` rows instead of explicit display columns | Project only `display_name`, `avatar_url`, and review fields on public routes |
| **Removed team member still views workspace projects** | Server read workspace IDs from a stale cached session claim instead of `workspace_members` | Query live `workspace_members` status on every workspace-scoped API request |
| **Private PDF receipt fails for the legitimate owner** | Storage download route checked `role === 'admin'` only instead of `owner OR admin` | Allow download when `invoice.user_id === session.user.id` or `session.user.role === 'admin'` |

> **Note:** **Pair row privacy with private storage.** Database rules protect your structured rows, while signed short-lived download URLs protect uploaded PDFs and ID scans. Review [File storage & uploads](https://exaspark.ai/docs/file-storage/) to lock down attachments with the exact same ownership checks.

## Next steps

- [Authentication & roles](https://exaspark.ai/docs/authentication-and-roles/) — Set up sessions, 19+ sign-in providers, and Guest/Member/Staff/Admin tiers.
- [Private & invite-only apps](https://exaspark.ai/docs/app-visibility-and-invites/) — Gate entire apps behind login walls, waitlists, and single-use invites.
- [Pre-launch security audit](https://exaspark.ai/docs/pre-launch-security-audit/) — Run a complete authorization, secrets, and storage checklist before launching.

## From the blog

- [App security basics](https://exaspark.ai/blog/app-security-checklist/) — Practical security habits every founder should verify before going live.
- [User roles and permissions](https://exaspark.ai/blog/user-roles-and-permissions/) — Designing clean permission boundaries across members, staff, and admins.
- [How sign-in works](https://exaspark.ai/blog/how-sign-in-works/) — Plain-English guide to sessions, cookies, identity, and authorization checks.
