# Multi-tenancy and security

Fellow isolates tenants in two layers: the code scopes every query to the tenant of the verified identity,
and PostgreSQL enforces it with forced row-level security. This page covers the platform around that core:
the tenant registry, audit, quotas, feature flags, retention, export and the checks that keep isolation honest.

## Tenant context

The tenant always comes from the verified identity (token or session), never from the URL, a header or the body.
Routes with `tenant: 'required'` run with that tenant bound to the request context; `sql` and `transaction`
set `app.tenant_id` for the transaction, and the RLS policies read it.

Background work carries the context explicitly:

```ts
import { captureContext, runWithEnvelope } from '@fellowframework/core'

const envelope = captureContext() // { tenantId, subject, roles, requestId }
// ... later, in a worker:
runWithEnvelope(envelope, () => work(), (e) => rebuildIdentity(e))
```

Permissions are never carried in the envelope: they are rebuilt from the roles with the current definitions.

## Tenant registry

`fellow_tenants` holds each organization: slug, name, status (`active`/`suspended`), domains, quota limits and settings.

```bash
fellow tenant:create city-x --name "City of X" --domain records.city-x.example
fellow tenant:suspend city-x
fellow tenant:limits city-x --set records.documents=5000
```

The registry is a policy layer on top of the identity, enabled in `app.ts`:

```ts
export default defineApp({
  tenancy: { verifyStatus: true, requireRegistered: true, verifyDomain: true },
})
```

| Option | Effect |
|---|---|
| `verifyStatus` | Suspended tenants get 403 `tenant.suspended` (default in new applications) |
| `requireRegistered` | Tenants missing from the registry get 403 `tenant.unknown` (recommended in production) |
| `verifyDomain` | When the request host is a registered tenant domain, the identity must belong to that tenant (`tenant.domain_mismatch`) |

The registry fails closed: if it cannot be read, tenant-scoped requests get 503 `tenant.registry_unavailable`.
Status is cached for 30 seconds per process.

## Audit log

```ts
import { audit } from '@fellowframework/core'

await audit('records.document.archived', { resource: { type: 'records.document', id }, data: { reason } })
```

- Entries are per tenant (RLS), redacted (passwords, tokens, cookies), and **append-only**: a database trigger
  rejects updates and deletes.
- Each entry is **hash-chained** to the previous one of the same tenant. `fellow audit <tenant> --verify`
  recomputes the chain and reports the first altered entry (FW-AUDIT-001), even when someone bypassed the trigger.
- `audit()` writes in its own transaction (an audited denial survives the rollback of the operation) and never throws.
- Routes audit declaratively: `audit: true` records successful executions with the route id as the action;
  every 403 of a tenant identity is recorded as `access.denied` (turn off with `auditDenials: false` in `app.ts`).
- The `accounts` module records `accounts.login` successes and failures.

## Contextual authorization

Permissions say what a role may do; `authorize` decides about this record, after input validation:

```ts
defineRoute({
  // ...
  access: { permission: 'records.document.update' },
  authorize: ({ input, identity }) => isAssignee(input.params.id, identity!.subject),
})
```

Returning false answers 403 and is audited. Policies (`definePolicy`) remain the place for reusable rules.

## Quotas

```ts
import { consumeQuota, defineQuota } from '@fellowframework/core'

export const documents = defineQuota({ name: 'records.documents', description: 'Documents per month', limit: 1000, period: 'month' })

await consumeQuota(documents) // 429 quota.exceeded when the limit would be passed
```

Consumption is atomic (concurrent requests cannot overshoot) and joins the caller's transaction, so a rolled-back
operation does not consume. Per-tenant limits override the default (`fellow tenant:limits`). `period: 'total'`
never resets; give units back with `releaseQuota`. Rate limits per tenant: `rateLimit({ limit, window, by: 'tenant' })`.

## Feature flags

```ts
import { defineFlag, isEnabled } from '@fellowframework/core'

export const signature = defineFlag({ name: 'records.digital_signature', description: 'Digital signature', default: false })
if (await isEnabled(signature.name)) { /* ... */ }
```

Precedence: tenant setting, then the global setting (with an optional percentage rollout, deterministic per tenant),
then the declared default. A route or page with `flag: 'records.digital_signature'` answers 404 while the flag is off.

```bash
fellow flag:set records.digital_signature --on --rollout 10
fellow flag:set records.digital_signature --off --tenant city-x
```

## Retention

Modules declare how long their data lives, in the manifest:

```ts
retention: [{ table: 'records_access_logs', days: 365, column: 'created_at', description: 'Access logs' }],
```

`fellow retention:run [--dry-run]` applies the policies per registered tenant, inside its context, and audits each
deletion. A module can only expire its own tables (FW-MOD-009). `FELLOW_AUDIT_RETENTION_DAYS` also prunes the audit log.

## Export

`fellow tenant:export <tenant>` writes one NDJSON file per table with tenant data, plus `manifest.json` with row
counts and SHA-256 of each file. It reads cross-tenant data, so it requires a human approval bound to that tenant:
`fellow approve tenant.cross <tenant-id>`. Session hashes are never exported. The export is audited.

## Verifying isolation

- `fellow doctor` checks the database catalog: every table with a `tenant_id` column must have row-level security
  enabled, forced and a tenant policy, unless a migration marks it `-- fellow:global <table>`. It also refuses roles
  that bypass RLS.
- `fellow make:isolation <module>` creates a test that seeds data as tenant A and calls every tenant-scoped route
  as tenant B with every permission (`app.checkIsolation`). Any 2xx on A's resource, or A's data in B's response, is a leak.

## Outbound requests

Use `safeFetch` for any URL a user or tenant can influence (webhooks, imports): only http(s), only public
addresses (no localhost, private networks or cloud metadata), redirects validated at every hop, and a timeout.
The webhook notification channel uses it; internal gateways are allowed with `allowHosts`.

## Secret rotation

Set the new secret in `FELLOW_SECRET` and the old one in `FELLOW_SECRET_PREVIOUS`. Tokens signed with the old
secret stay valid until they expire; new tokens use the new one. Remove `FELLOW_SECRET_PREVIOUS` afterwards.

## Logging

`log.info(event, fields)` writes JSON lines with request id, tenant and subject, and redacts secrets by key
(password, token, cookie, authorization...) and by value (bearer tokens, JWTs, credentials in URLs).
`FELLOW_LOG_LEVEL` sets the minimum level; `configureLogger` sends entries elsewhere.
