- Security
- MongoDB
- Go
Multi-tenancy you can trust: making the data layer refuse to leak
The most damaging bug a restaurant SaaS can ship is one restaurant seeing another’s customers or takings. A filter someone forgot is the usual cause. So we built Fravolo where that filter is not something you can forget to write, because the code that talks to the database adds it for you, every time.
Discipline does not scale; structure does
Every business document in Fravolo — an order, a menu item, a KOT, a customer, a print job — carries a tenant_id naming the restaurant it belongs to, and an outlet_id where it belongs to a branch. The obvious way to keep restaurants apart is to remember to add tenant_id to every query. That works until the hundredth endpoint, written late on a Thursday, that does not.
We took that choice away. Modules never hold a raw database collection for business data. They ask for one through m.On(ctx, name), and what they get back is a wrapper that is already bound to the caller’s restaurant. It cannot be pointed at another one.
Where the restaurant comes from
Authentication middleware verifies the session and builds a Scope: the restaurant, the active outlet and the outlets this person may see, the user and their role, and the restaurant’s currency and time zone. The scope is put into the Go context under a private key, so nothing outside the tenancy package can forge one.
Crucially, the restaurant id never comes from anything the client sends in a body or a query string. Staff get it from their session; a restaurant’s own website gets it from its signed API key; a paired counter device gets it from its device key. If a route does not have a scope, a guard refuses it before any handler runs.
type Scope struct {
TenantID string
DefaultOutletID string // the active outlet
OutletIDs []string // outlets this member may see
UserID string
Role string
Currency string
Timezone string
}
// From returns the caller's scope. An empty restaurant is not a scope.
func From(ctx context.Context) (Scope, bool) {
s, ok := ctx.Value(ctxKey{}).(Scope)
return s, ok && s.TenantID != ""
}A collection that rewrites every operation
The wrapper exposes the operations modules need — find, count, insert one or many, update one or many, find-and-update, replace, delete one, aggregate — and each one is rewritten on the way through:
- Filters have the restaurant ANDed in. If the filter already names a *different* restaurant, the call fails with an error rather than quietly overriding it: a filter like that is a bug, and we want to hear about it.
- Inserts are stamped with the restaurant. A document that arrives carrying another restaurant’s id is refused.
- Updates cannot unset or rename
tenant_id, and any$setof it is pinned back to the caller’s restaurant — which also protects against a request struct that decodes an empty value into the field. - Aggregations get a
$matchon the restaurant prepended as the first stage, so every pipeline starts inside one tenant — and stages that would reach outside it are refused anywhere in the pipeline, nested stages included:$lookup,$unionWithand$graphLookup(which read other collections) and$outand$merge(which write to them). The leading$matchcannot reach inside those, so they are not allowed at all. A scoped pipeline reads one restaurant’s documents in one collection, and nothing else. - Pipeline-style updates — the aggregation form of an update — may only set, add or unset fields, never
tenant_id; stages that could drop or replace the whole document are refused.
// scope ANDs the caller's restaurant into a filter.
func (c *Coll) scope(filter any) (bson.M, error) {
out, err := toM(filter)
if err != nil {
return nil, err
}
if v, ok := out["tenant_id"]; ok && v != c.tenant {
return nil, ErrTenantInDoc // never silently override
}
out["tenant_id"] = c.tenant
return out, nil
}
func (c *Coll) Find(ctx context.Context, filter any, o ...*options.FindOptions) (*mongo.Cursor, error) {
if c.err != nil {
return nil, c.err // no scope, unclassified, or moving
}
f, err := c.scope(filter)
if err != nil {
return nil, err
}
return c.c.Find(ctx, f, o...)
}Just as important is what the wrapper leaves out. There is no `DeleteMany`: a module can delete one document it has named, never a filter’s worth. Tax documents are never deleted at all; they are cancelled with credit notes, which we wrote about in the invoice-numbering post.
Failing closed
Ask for a business collection without a scope and you do not get an unscoped collection. You get a wrapper whose every method returns ErrNoScope. The same goes for a collection name nobody has classified: every collection is listed once, as core (identity and routing: restaurants, users, memberships, devices and so on) or business (everything a restaurant owns), and an unlisted name fails every call with an error that says which file to edit.
func (c *Client) On(ctx context.Context, name string) *tenancy.Coll {
if IsCore(name) {
return tenancy.On(ctx, c.db, name)
}
if !IsBusiness(name) {
return tenancy.Failed(fmt.Errorf("collection %q is not classified (collections.go)", name))
}
s, ok := tenancy.From(ctx)
if !ok {
return tenancy.Failed(tenancy.ErrNoScope)
}
p, err := c.place(ctx, s.TenantID) // which database holds this restaurant
if err != nil {
return tenancy.Failed(err)
}
col := tenancy.Bind(p.db.Collection(name), s.TenantID)
if p.moving {
col.ReadOnly(tenancy.ErrMoving)
}
return col
}Indexes follow the same rule. A migration helper prepends tenant_id to every business index, so uniqueness — one customer per phone number, one bill per number — is per restaurant. Two restaurants can each have a customer on the same number, and they are two different customers.
Placement: the restaurant decides which database
Notice the place call above. Every restaurant has a placement: which cluster and database hold its business collections. New restaurants share a database and are kept apart by tenant_id. A larger group, or one with data-residency needs, can be moved to its own database or its own cluster without a code change, because nothing in a module knows where its data lives.
- 1Freeze. A conditional update marks the restaurant as moving. Each API instance caches placement for a few seconds, so the move waits long enough for every instance to see it. From then on the wrapper is read-only for that restaurant: reads work, writes get a “moving, retry shortly” answer, and every other restaurant carries on writing.
- 2Copy. Indexes are created on the target first, any stale copy of this restaurant there is cleared, then each business collection and file bucket is copied in batches.
- 3Verify. For every collection, the count in the source, the count copied and the count in the target must all agree. Any difference is an error.
- 4Switch, or roll back. The placement flips only if the move record still matches. Any failure deletes the target copy and restores the old placement. The source was only ever read, so a failed move leaves the restaurant exactly as it was.
If the process restarts mid-move, it rolls back interrupted moves on boot rather than trying to resume them. The old copy stays in place until it is removed deliberately, as a separate step.
The few paths without a session
Some requests arrive with no session at all: a guest opening their bill from a link, a payment provider’s webhook. For those we keep a small lookup table in the core database mapping an unguessable token to a restaurant. The lookup is the only unscoped step. Once the restaurant is known, the rest of the work builds a scope and goes back through the same wrapper. Inserting a lookup is itself guarded, so one restaurant cannot claim a token that belongs to another.
Background jobs are the other cross-tenant path. A sweep groups restaurants by the database they live in, finds candidate documents for exactly those restaurants, and then handles each one under a fresh system scope for its own restaurant. A stale copy left behind by a move is never picked up, because it is not in that database’s list.
Testing it with two real restaurants
Unit tests cover the wrapper’s rewrites. The test we trust most is an isolation suite that starts the real HTTP server against a real MongoDB, creates two restaurants, and tries to cross the line in every way we can think of:
| What the test does | What must happen |
|---|---|
| Read restaurant B’s bill or customer by id as A | Not found — not forbidden, which would confirm it exists |
| Update or cancel B’s records as A | Refused, and B’s data unchanged afterwards |
| List, report and export as A | Only A’s rows |
| Subscribe to the live event stream and push devices | Only A’s events and devices |
| Same guest phone number at both restaurants | Two separate customers |
| Switch into a restaurant you are not a member of | Refused |
| Remove a staff member, then refresh their session | Access ends |
The suite runs twice: once with both restaurants in one database, and once after moving one of them to a second cluster. A separate placement suite checks that a failed move rolls back with the source untouched, that writes are refused and reads still served during the freeze while another restaurant keeps writing, and that moving back clears the stale copy. Both run in CI on every push, against a MongoDB service started for the job, and every new endpoint gets a case in the isolation suite.
Trade-offs
- Escape hatches exist. Index management, migrations and cross-tenant sweeps need the raw driver. The raw escape hatch on a scoped collection is guarded by CI: a script fails the build if any non-test file outside a one-file, reviewed allow-list calls it, so a new one is a visible change with a reason attached. Sweeps and migrations that use the driver directly are still reviewed by hand, and we keep that list short on purpose.
- Verification counts documents; it does not hash them. Counts catch a truncated copy, which is the realistic failure. Content hashes would catch more and cost a second full read; we would add them before moving very large restaurants.
- A move blocks writes while it copies. For a restaurant of today’s size that is short, and we schedule moves outside service. A change-stream based live copy would remove the freeze, at the cost of much more code.
- Joins have to be done in code. Refusing
$lookupinside scoped pipelines means a report that needs two collections reads each through its own scoped wrapper and joins in Go. That is more code and an extra round trip, and it is the right trade: the alternative is a join stage that has to remember the tenant filter on its own.