> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reliantlabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Scope rows to their owner in a multi-tenant API

> Make each signed-in user see and change only their own rows: declare a forge:owner column, finish the scaffolded owner filter and prove it with a two-user test.

You will make an `orders` table where each signed-in user sees and changes only their own rows, then retrofit the same rule onto a table that already exists. The filter is ordinary Go in your handler file. Forge scaffolds it and checks that it stays there, but never injects a `WHERE` clause at runtime.

[The security model](https://docs.reliantlabs.io/deep-dives/security-model.md#2-you-write-the-access-rules-and-the-audit-finds-the-gaps) explains why the rule is code you own.

## Before you begin

* The `shop` project from [Add a database table with a CRUD API and pages](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md). Any forge API works the same way.
* Forge v1.6.1 or later, run as `reliant forge` inside the project.
* [Find API endpoints that never check who is calling](https://docs.reliantlabs.io/guides/forge/find-endpoints-missing-auth-checks.md) shows the audit this guide uses to confirm the result.

**1. Declare who owns a row**

Mark the owner field on the entity before you scaffold it. `forge:read-only` keeps it off the create request, so the server stamps it from the caller instead.

```protobuf proto/services/catalog/v1/catalog.proto theme={null}
// forge:entity
message Order {
  string owner_id = 2; // forge:read-only forge:owner
  string product_id = 3;
  int32 quantity = 4;
}
```

**2. Scaffold the entity**

```bash terminal theme={null}
reliant forge scaffold
```

```text theme={null}
  entities birthed:    1 (services.catalog.v1.Order → orders)
```

The migration records the declaration in the schema, where forge reads it from now on:

```sql db/migrations/20261120100303_create_orders.up.sql theme={null}
COMMENT ON COLUMN orders.owner_id IS 'forge:owner';
```

Every Order handler in `handlers_crud.go` resolves the caller and adds the owner to the query: Get, Update and Delete match `owner_id`, List filters before it counts, and Create and Update stamp the column. Another user's row reports `not_found`, the same as an id that doesn't exist, so a caller can't probe which ids are real.

**3. Map the caller to the owner value**

Each of the five wrappers leaves one decision to you:

```go internal/handlers/catalog/handlers_crud.go theme={null}
	// FORGE_SCAFFOLD: `claims.UserID` is forge's placeholder for the value of
	// Order.owner_id that belongs to this caller. Only your app
	// knows that mapping — replace the expression, then remove this comment.
	owner := claims.UserID
```

`claims.UserID` is the token's subject. Keep it if `owner_id` stores that id; for rows owned by a team, use a column holding the org and `claims.OrgID`. Use a stable id, never an email address. Make the same choice in all five wrappers, then delete the `FORGE_SCAFFOLD` comments. `lint --conventions` flags a wrapper whose owner source differs from its siblings'.

**4. Confirm with the audit**

```bash terminal theme={null}
reliant forge project audit --json | jq '.categories.unscoped_auth | {summary, owner_scoped_tables: .details.owner_scoped_tables, scoped: .details.scoped_rpcs}'
```

```json jq output theme={null}
{
  "summary": "10 of 15 authenticated RPC(s) never resolve the caller — every signed-in caller is treated identically (middleware.GetUser)",
  "owner_scoped_tables": ["orders"],
  "scoped": 5
}
```

The five Order RPCs are scoped. The other ten were unscoped before this guide. Declaring the owner also armed a gate: if someone later replaces `GetOrder` with a plain delegation, the audit fails.

```text theme={null}
✗ unscoped_auth — 1 authenticated RPC(s) over forge:owner-declared data never resolve the caller — ...: CatalogService.GetOrder (orders)
```

`reliant forge project audit` then exits 1, and the JSON's `owner_scoped_unscoped_rpcs[].remediation` holds the wrapper to paste back.

**5. Prove it with two users**

The audit proves each handler reads the caller. A test proves the filter. Create an order as one user and try every operation as another:

```go internal/handlers/catalog/order_owner_test.go theme={null}
func asUser(id string) context.Context {
	return middleware.ContextWithClaims(context.Background(), &middleware.Claims{UserID: id})
}
```

```bash terminal theme={null}
task test:short -- -v -run TestOrder_OwnerScoping ./internal/handlers/catalog/...
```

```text theme={null}
    order_owner_test.go:28: alice created 01M7W7RXBAZFAGMZH6TMHJXPV2, owner_id="alice"
    order_owner_test.go:35: bob GetOrder: not_found: order not found
    order_owner_test.go:44: bob ListOrders: 0 rows, total_count=0
    order_owner_test.go:51: bob UpdateOrder: not_found: order not found
    order_owner_test.go:57: bob DeleteOrder: not_found: order not found
--- PASS: TestOrder_OwnerScoping (0.12s)
```

Bob's update sent `owner_id: "bob"` in the body. It was still refused, because the predicate is checked against the stored row.

**6. Scope a table that already exists**

`handlers_crud.go` already exists for `reviews`, so declaring an owner can't regenerate it. Add the column and the comment in a new migration, and the field to the `Review` message (`string author_id = 9; // forge:read-only`):

```bash terminal theme={null}
reliant forge db migration new add_reviews_author --backward-compatible "new column with a default; the previous release never reads it"
```

```sql db/migrations/20261120102807_add_reviews_author.up.sql theme={null}
ALTER TABLE reviews ADD COLUMN author_id TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN reviews.author_id IS 'forge:owner';
```

Existing rows get an empty owner, which no caller matches; backfill them in the same migration if you know their authors. Run `reliant forge generate`. The audit now fails for all five Review RPCs and prints each wrapper:

```bash terminal theme={null}
reliant forge project audit --json | jq -r '.categories.unscoped_auth.details.owner_scoped_unscoped_rpcs[] | select(.method=="DeleteReview") | .remediation'
```

Paste the wrappers for Create, Update and Delete over the plain delegations. Reviews are public to shoppers, so mark the two reads instead: `// forge:auth-unscoped-ok: every signed-in shopper reads every review; only writes are the author's`. With the product RPCs handled as in the previous guide, the audit is clean:

```text theme={null}
✓ unscoped_auth — all 15 authenticated RPC(s) resolve the caller
```

A test like the one above confirms that Bob can read Alice's review but `DeleteReview` returns `not_found: review not found` for him.

## What this does not do

* **No runtime filter.** Forge never adds a `WHERE` clause on its own. A query you write yourself, in a custom RPC or `internal/db/*_repo_ext.go`, needs its own filter, and the audit can't arm the gate for a custom RPC.
* **No database row-level security.** The rule lives in the API. Anything that connects to Postgres directly bypasses it.
* **No roles or sharing model.** One column names one owner. Shared rows, teams with several roles, or admin overrides are handler code you add.
* **The audit can't judge your mapping.** It checks that each handler reads the caller, not that `owner` holds the right value; your tests do that.

## Troubleshooting

> [accordion] \[forgeconv-crud-owner-resolver] … scopes owner\_id by …
>
> The wrappers for one entity resolve the owner in different ways. Make every wrapper use the same expression. While one still reads `claims.UserID` with its `FORGE_SCAFFOLD` comment, the lint treats it as undecided and suggests the other source, so read the suggestion before you apply it.

> [accordion] The proto marker did nothing on an existing entity
>
> `// forge:owner` on a proto field is read only when the entity is scaffolded. On an existing table, use the migration path in the last step.

> [accordion] Every List returns zero rows
>
> The owner values in the table don't match what the wrapper computes from the claims. Check rows created before the column existed (empty owner) and that all wrappers use the same claim.

## Next steps

> [card] [Find unchecked endpoints](https://docs.reliantlabs.io/guides/forge/find-endpoints-missing-auth-checks.md)
>
> List every RPC that never reads the caller, and add role checks

> [card] [Security model](https://docs.reliantlabs.io/deep-dives/security-model.md)
>
> Fail-closed auth, the owner gate and error redaction

> [card] [Add sign-in](https://docs.reliantlabs.io/guides/forge/add-sign-in-passkeys.md)
>
> Passkeys, magic links or social login, and the RPCs that stay public

> [card] [Zero-downtime migrations](https://docs.reliantlabs.io/guides/forge/zero-downtime-postgres-migrations.md)
>
> Add the owner column without breaking the running release


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.