Plugin

Multi-tenancy

One user, many organizations, a different role in each, with query scoping that can't be forgotten.

grit plugin add multitenant
cd apps/api && go run cmd/migrate/main.go

Why a plugin

Most apps are single-tenant, and putting org_id on every table is a schema decision no framework should make for you. Install it when you need it.

Marking a model as tenant-owned

Embed tenant.Owned. That's what opts a table into isolation:

type Invoice struct {
ID string
Amount int
tenant.Owned // adds OrgID + the index
}

Generated resources are shared until you do this.

grit generate resource does not know this plugin is installed, so a model it writes has no OrgID and no scoping. That is the right default for a shared table like a country list, and the wrong one for anything belonging to a customer. Open the model and embed tenant.Owned for each resource that belongs to an organization, and remember it again after any --force regeneration.

Scoping applies per model, so a table without OrgID is simply never filtered. Nothing warns you: the endpoint works, returns rows, and returns everyone's.

Then just query normally: scoping is applied for you:

// Only the active organization's invoices.
db.WithContext(ctx).Find(&invoices)
// OrgID is stamped on insert; you never set it.
db.WithContext(ctx).Create(&Invoice{Amount: 100})
Scoping fails closed

A query against a tenant-owned model with no active organization returns an error. It does not quietly return every tenant's rows. Hand-written scoping fails the other way: forget one WHERE and you get a silent cross-tenant leak that no test catches, because the query returns more rows rather than failing.

Cross-tenant work

Platform admin screens and background sweeps need to see everything. Opt out explicitly, so each call is deliberate and greppable:

tenant.Unscoped(db).Find(&allInvoices)

How the active organization is chosen

From the X-Organization-ID header, or automatically when the user belongs to exactly one. No subdomains: they force DNS and TLS decisions on every deployment and make local development awkward.

curl https://api.example.com/api/invoices \
-H "Authorization: Bearer ..." \
-H "X-Organization-ID: 01H..."

Membership is always verified against the database. Trusting the header alone would let any signed-in user read another tenant's data by editing one request header.

Requesting an organization you don't belong to returns 404, not 403. A 403 confirms it exists and lets an attacker enumerate tenants.

When there is no active organization

A tenant-owned row cannot be read or written without one, and the scoping callback fails closed rather than guessing. The caller is told so: 400 with the code NO_ORGANIZATION, which happens when they belong to no organization, or to several and named none.

400 Bad Request
{
"error": {
"code": "NO_ORGANIZATION",
"message": "no active organization: send it as X-Organization-ID, or join one"
}
}

Until v3.233.0 this arrived as a 500 saying "Failed to fetch deals", because the error reached the generic handler and nothing knew what it meant.

Roles per organization

Membership carries a role, so somebody can be an editor in one organization and a viewer in another. It reuses the roles you already have, with no parallel permission system.

# Give Dave the "Deal Closer" role, in this organization only
curl -X POST https://api.example.com/api/v1/organizations/01H.../members \
-H "Authorization: Bearer ..." \
-d '{"user_id": "01H...", "role_id": "01H..."}'

The semantics, because they are a choice: an organization role adds permissions inside that organization. Platform roles, the ones assigned with PUT /users/:id/roles, stay global. So an organization can grant but cannot take away, and a project with no membership roles behaves exactly as it did.

This is what v3.233.0 fixed: the membership role was stored, put on the request context, and read by nothing, so being an administrator of one organization meant being one in every organization you belonged to.

Single sign-on does not join an organization

A user provisioned by SSO or a social login belongs to no organization, so every tenant-owned endpoint answers NO_ORGANIZATION for them until somebody puts them in one. That is deliberate: which organization a new user joins is a policy the framework cannot guess, and guessing would be a cross-tenant bug rather than a convenience. Map it where you know it, from the email domain, the SSO connection, or a group the identity provider releases. grit doctor reminds you when both are present.

Adding it

grit new <name> --multitenant at scaffold time, or grit plugin add multitenant in a project that already exists. Both go through the same install, so they write the same project.

Either way, nothing is scoped until you say which models are owned. Add tenant.Owned to a model, or generate it with --tenant-owned. That is deliberate: putting org_id on every table is a schema decision no framework should make for you, and a model that is shared on purpose (a currency table, a country list) would be the thing it broke.

Choosing the active organization

Clients send it as X-Organization-ID. A user who belongs to exactly one organization has it activated automatically and never sends the header at all.

A user who belongs to two gets a switcher in the admin, which the plugin installs. It renders nothing below two organizations, so a single-tenant project looks as it did. Switching clears the React Query cache rather than invalidating it: an invalidated query serves its old data while it refetches, and that data belongs to the organization being left.

The header itself is the framework's, in lib/active-org.ts and the api-core interceptor, and it is present in every project whether or not the plugin is. It sends nothing until something sets a value, so a single-tenant project carries a few inert lines and nothing else.

An organization has roles of its own

A role's name is unique per owner, not across the platform, so two customers can each have an "Accountant" and an edit by one does not change the other's permissions. A role with an empty owner_org_id is the platform's; one carrying an organization's id belongs to that organization, is listed only through that organization's endpoint, and cannot be read, edited or handed out by anybody else.

Who may author one: the organization's owner, a platform administrator, or a member holding orgroles.manage. Who may change the membership: the same three, with orgmembers.manage. Nothing grants either by default, so until the owner authors such a role only they can do these things, which is the safe default rather than the convenient one.

What an organization's role may hold

Never *, and never the platform's own administration: users., roles., settings., apikeys., audit. and the rest. A membership role's grants are merged into every request made with that organization active, and the platform's routes check the permission key rather than who owns the role, so one of those in a customer's role is that customer reading everybody's data.

Beyond that, the ceiling is the author's own grants, with one widening for the owner, who holds no role by default and would otherwise be refused every role they tried to write. An owner may hand out a permission they do not hold when the model behind it is tenant-owned: the tenant callback scopes it to the organization in the request, so a member holding it sees their own rows. On a model with no org_id the identical grant hands them every organization's rows, so it is refused, and the refusal says which model and what to do about it. The schema is the only thing that knows the difference, so the schema is what gets asked.

Endpoints

GET /api/organizations orgs you belong to
POST /api/organizations create (you become owner)
GET /api/organizations/:id/members
POST /api/organizations/:id/members
DELETE /api/organizations/:id/members/:userId
GET /api/organizations/:id/roles any member may read
POST /api/organizations/:id/roles owner, admin, or orgroles.manage
PUT /api/organizations/:id/roles/:roleId
DELETE /api/organizations/:id/roles/:roleId refused while anybody holds it
Adding this to an existing app

Existing rows have no org_id. Before adding tenant.Owned to a model that already has data, create a default organization and backfill it, or those rows become invisible to every scoped query.

Using it, step by step

Taking a single-tenant project to one where a user belongs to several organisations and holds a different role in each. Nothing is scoped until you say which models are owned, which is step 3.

Install it

grit plugin add multitenant

Writes the Organization and OrganizationMember models, the tenant package holding the GORM callbacks, the organisation screens in the admin, and the switcher in the navbar.

Run the migration

cd apps/api && go run cmd/migrate/main.go

Creates the two tables. Nothing else in the project has changed shape yet.

Make a model tenant-owned

type Deal struct {
ID string `gorm:"primarykey;size:36" json:"id"`
Title string `json:"title"`
tenant.Owned // <- this line is the whole opt-in
}

Embedding tenant.Owned adds OrgID and brings the model under scoping. Until a model has it, it stays shared across organisations, which is the right default for a currency table and the wrong one for a deal.

Migrate again, and backfill

cd apps/api && go run cmd/migrate/main.go

The new org_id column starts empty on existing rows, and an empty org_id matches no organisation. Rows that predate this are invisible to every scoped query until you give them one, so backfill before anybody looks.

Tell the API which organisation is active

curl -H "X-Organization-ID: org_123" localhost:8080/api/v1/deals

The admin and web clients send this header automatically once an organisation is selected. Without it a scoped query fails closed with NO_ORGANIZATION rather than returning everything.

Opt one query out, visibly

// A platform-wide report, deliberately across organisations.
var total int64
tenant.Unscoped(db).Model(&models.Deal{}).Count(&total)

Scoping is automatic so that forgetting is impossible; the escape hatch is explicit so that crossing tenants shows up in review. Read internal/tenant/tenant.go before using it.

Related plugins

Near neighbours, and what each one is for instead.

Everything else is on the marketplace, and four ways to extend says when a plugin is the wrong tool for the job.