Aviary
Concepts

Tenancy

Scope media records and upload sessions by the request's tenant (organization), from @dudousxd/nestjs-context. Off until you turn it on.

With tenancy on, every media record and upload session belongs to the tenant of the request that created it (an organization, a clinic, a user's workspace), and a request only sees its own tenant's media. The tenant comes from @dudousxd/nestjs-context; media reads it structurally and doesn't depend on it.

Tenancy is off by default. Nothing changes until ContextModule turns it on, and a table without the tenant column keeps working while it is off.


Turn it on

  1. Add the nullable tenant_id column to your tables (per adapter, below).
  2. Turn tenancy on in the context, and set the tenant of each request (see the context's Tenancy page):
ContextModule.forRoot({ tenancy: { enabled: true } });

// in your auth guard, once the organization is resolved:
Context.setTenant({ id: claims.org_id, kind: 'organization' });

MediaModule follows the context switch. Its own tenancy option overrides it:

MediaModule.forRoot({
  store,
  tenancy: 'inherit', // default: on when ContextModule turns tenancy on
});
tenancyEffect
'inherit' (default)On when ContextModule's tenancy.enabled is true
falseOff, even when the context turns tenancy on
an objectThe fields below.

The object form takes:

FieldEffect
enabled?: 'inherit' | booleanOverrides the context switch.
kinds?: string[]Media's own allow-list of tenant kinds. With nested tenants, media scopes by the most specific level of the active chain whose kind is listed. A tenant with no listed level counts as none.
family?: stringScope by the request's tenant of this family (e.g. a patient's account) instead of the primary one.
required?: booleanA read or write with no tenant throws the context's TenantRequiredError (403) instead of running as tenantless. Default: the context's tenancy.required. See Require a tenant.
nullRows?: 'tenantless' | 'shared''shared' shows records with no tenant to every tenant. Default 'tenantless'.
pathPrefix?: booleanStore new library files under t/<tenantId>/. Default false. See Tenant folders.

What changes

Writes are stamped. library.attach() (and MediaService.attach()), and resumable uploads (uploads.createUpload(), the tus and multipart controllers), store the request's tenant id. A request with no tenant stores null.

An explicit tenantId wins over the request's tenant, for example in a job or a webhook handler:

await media.library.attach({ ...input, tenantId: invoice.organizationId });
await media.uploads.createUpload({ disk: 's3', key, tenantId: null }); // no tenant

tenantId is ignored while tenancy is off.

Reads follow the request's tenant. library.get(), library.list(), library.locate(), library.url(), conversions (ensureConversion), MediaService.serve()/url()/delete(), upload sessions (status, writeChunk, writePart, complete, abort) and the dashboard's library and uploads views apply this rule:

RequestRecord of its tenantRecord of another tenantRecord with no tenant
with a tenantvisiblenot foundnot found (visible with nullRows: 'shared')
with no tenant—not foundvisible
inside Context.allTenants()visiblevisiblevisible
no context (boot, workers, scripts)visiblevisiblevisible

A record or session the request can't see is treated exactly like a missing one, never as a 403, so other tenants' ids don't leak:

  • Library (locate(), url(), ensureConversion): MediaNotFoundError. get() returns null.
  • Upload sessions (status, writeChunk, writePart, complete): UploadSessionNotFoundError.
  • MediaService.serve()/url(): a 404.
  • library.delete(), MediaService.delete() and upload abort(): a silent no-op. Nothing is deleted, and nothing is thrown.
  • Dashboard: every library and uploads endpoint returns a 404, including delete record and cancel upload. With tenancy on, deleting or cancelling a missing id is a 404 too. The check runs before your authorize hook, which still runs for every visible record: tenancy only narrows.

The console shows the tenant. With tenancy on, the dashboard's library cards, record detail, uploads table and upload detail show each row's organization. The label comes from the context's tenancy.label resolver (context ≥ 2.1), else the tenant's id. The JSON API returns it as tenant: { id, label } (null for a row with no tenant).

Not scoped by tenant: the dashboard's object browser unless pathPrefix is on (it lists raw disk keys, not records), direct presigned uploads (they keep no session), the attachment-as-column API (attachments live on your own rows), and the Telescope media panels. Restrict those with your authorize hooks.


Nested tenants

When tenants nest (a clinic and its units), the context carries the active chain, root first (context ≥ 2.1):

Context.setTenant({ id: unit.id, kind: 'unit', chain: [{ id: clinic.id, kind: 'clinic' }] });

Pick the level media scopes by with kinds:

MediaModule.forRoot({ store, tenancy: { kinds: ['clinic'] } }); // files belong to the clinic
MediaModule.forRoot({ store, tenancy: { kinds: ['unit'] } });   // files belong to the unit

Files are stamped with that level's id, and a request sees the files of that level. With kinds: ['clinic'], every unit of a clinic shares the clinic's files. Without kinds, media uses the tenant itself (the most specific level). With an older context there is no chain, and the tenant is used as before.


Require a tenant

With required on (in ContextModule's tenancy, or in media's own option), a library read or write, an upload, or a console read with no tenant throws TenantRequiredError: a 403 with code: 'E_TENANT_REQUIRED'. A request inside Context.allTenants(), and code with no context at all (a script, a worker outside a request), still sees every row.

Media never throws it where no request is served: the boot check below reads tenancy with required: false. The console's global search answers no hits instead of failing. Set required: false in media's option to keep media lenient while other libs require a tenant.


Tenant folders (pathPrefix)

MediaModule.forRoot({ store, tenancy: { pathPrefix: true } });

With pathPrefix on, library.attach() stores a tenant's new files under t/<tenantId>/ (e.g. t/org_1/Post/42/gallery/<id>/photo.jpg). Their conversions sit next to them. That gives each tenant its own folder for bucket policies, lifecycle rules or an export.

  • Existing files never move. Records keep the key they were stored under, so old and new layouts work side by side.
  • A file with no tenant, or attached while tenancy is off, keeps the usual layout.
  • Characters a key segment can't hold (/, \, control characters) become _ in the tenant id.
  • Keys you choose yourself (resumable and direct uploads take the key you pass) are not prefixed. Build them under t/<tenantId>/ if you want the same layout.

The console's disks

With pathPrefix on, a viewer of one tenant browses the disks only inside their own t/<tenantId>/. That covers the object browser (list, preview, download, upload, new folder, rename, copy, move, delete), the console's dev tools and the console search:

  • Above that folder (the disk root, t/), the browser shows just the way down to it.
  • Any key outside it is a 404, like a missing one. That includes another tenant's folder, files stored before pathPrefix was on, and keys that try to climb out (.., encoded slashes, a leading /).
  • A request with no tenant sees no disk object.
  • A viewer of every tenant (Context.allTenants(), the system scope, or tenancy off) still sees every key, files from before pathPrefix included.

With pathPrefix off, the object browser is not scoped by tenant.

Library records are scoped by their tenant, not by their key. A tenant's records stored before pathPrefix still show in the library, but their keys aren't reachable through the object browser.


Fails at boot, not at the first request

With tenancy on, MediaModule checks at boot that the media store (and the upload session store) can scope by tenant. When the tenant_id column is missing, the app refuses to start with MediaTenancyUnavailableError, whose message says how to add it. A store that doesn't implement tenancy (enableTenancy()) fails the same way.

With tenancy off, the stores never read or write the column, so you can add it before you turn tenancy on.


Schema

Each adapter declares a nullable tenant_id and an index on (tenant_id, owner_type, owner_id, collection) (upload sessions: (tenant_id)). Add them the way the adapter already manages its schema:

AdapterHow the column gets there
TypeORMMediaEntity declares it. With autoCreateSchema (default), the store adds the column and index when tenancy turns on; with synchronize, TypeORM adds them; otherwise a migration.
MikroORMMediaEntity declares it. ensureMediaSchema(orm) adds it, or generate a migration with the MikroORM CLI.
DrizzlemediaTable, mediaPgTable and mediaUploadSessionsPgTable declare it: generate a migration with drizzle-kit. createMediaTable / createMediaPgTables add it in dev and tests.
PrismaAdd tenantId String? @map("tenant_id") and the index to your Media model, then prisma migrate dev.
Redis sessions, in-memory storesNothing to add.

Plain SQL, if you write migrations by hand:

ALTER TABLE media ADD COLUMN tenant_id varchar(255) NULL;
CREATE INDEX idx_media_tenant ON media (tenant_id, owner_type, owner_id, collection);
-- MySQL (utf8mb4): prefixes keep the key under InnoDB's 3072 bytes
-- CREATE INDEX idx_media_tenant ON media (tenant_id(191), owner_type(191), owner_id(191), collection(191));

-- Drizzle Postgres upload sessions
ALTER TABLE media_upload_sessions ADD COLUMN tenant_id text NULL;
CREATE INDEX idx_media_upload_sessions_tenant ON media_upload_sessions (tenant_id);

The TypeORM adapter names its owner columns ownerType / ownerId (camelCase): use ("tenant_id", "ownerType", "ownerId", "collection") there.


Backfill existing records

Records created before tenancy have tenant_id = NULL: only requests with no tenant see them. Assign them once, in SQL, from the owner they belong to.

When the owner is the tenant (media attached to an Organization):

UPDATE media
SET tenant_id = owner_id
WHERE tenant_id IS NULL AND owner_type = 'Organization';

When the owner belongs to a tenant (a Project with an organization_id):

UPDATE media
SET tenant_id = projects.organization_id
FROM projects
WHERE media.tenant_id IS NULL
  AND media.owner_type = 'Project'
  AND projects.id::text = media.owner_id;

That is Postgres syntax; on MySQL use UPDATE media JOIN projects ON projects.id = media.owner_id SET media.tenant_id = projects.organization_id WHERE .... Repeat per owner type. Records you leave NULL stay visible to requests with no tenant (and to every tenant with nullRows: 'shared').

Upload sessions are short-lived: let in-flight ones finish rather than backfilling them.


Custom stores

A custom store supports tenancy by implementing enableTenancy(): check (or add) the column and throw when it's missing; from then on, persist record.tenantId and honour the tenant field of the count / aggregate / list filters ({ id: string | null; orNull?: boolean }, where id: null means "no tenant"). Until enableTenancy() is called, never touch the column. runMediaStoreConformance covers it.


Testing

import { Context } from '@dudousxd/nestjs-context';

it('keeps tenants apart', async () => {
  const mine = await Context.withTenant({ id: 'org_1', kind: 'organization' }, () =>
    media.library.attach(input),
  );
  const seen = await Context.withTenant({ id: 'org_2', kind: 'organization' }, () =>
    media.library.get(mine.id),
  );
  expect(seen).toBeNull();
});

InMemoryMediaStore and InMemoryUploadSessionStore from @dudousxd/nestjs-media-testing support tenancy as they are.

On this page