Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
📍 fix: Pin Persisted Saves to Their Tenant (#15582)
Danny Avila6cd6be67de35
diff --git a/packages/data-schemas/src/models/plugins/tenantIsolation.ts b/packages/data-schemas/src/models/plugins/tenantIsolation.tsindex 9173215024..e96083287d 100644--- a/packages/data-schemas/src/models/plugins/tenantIsolation.ts+++ b/packages/data-schemas/src/models/plugins/tenantIsolation.ts@@ -7,6 +7,7 @@ import {resolveTenantScope,stampTenantOnDocument,sanitizeTenantMutation,+ tenantWritePredicate,resetTenantStrictCache,warnOnInvalidStrictSetting,} from '~/tenant/policy';@@ -28,6 +29,70 @@ warnOnInvalidStrictSetting();const TENANT_ISOLATION_APPLIED = Symbol.for('librechat:tenantIsolation');+interface TenantWhereDocument {+ $where?: Record<string, unknown>;+}++interface TenantSaveDocument extends TenantWhereDocument {+ get(path: string): unknown;+ set(path: string, value: unknown): void;+ unmarkModified(path: string): void;+}++interface TenantWhereState {+ readonly injectedTenantPredicate: unknown;+ readonly hadTenantId: boolean;+ readonly tenantId: unknown;+}++const tenantWhereStates = new WeakMap<TenantWhereDocument, TenantWhereState>();++interface TenantStampState {+ readonly injectedTenantId: string;+ readonly tenantId: unknown;+}++const tenantStampStates = new WeakMap<TenantSaveDocument, TenantStampState>();++/** Restores the document's own `$where.tenantId` before deriving the next save predicate. */+function restoreTenantWhere(document: TenantWhereDocument): void {+ const state = tenantWhereStates.get(document);+ const where = document.$where;+ tenantWhereStates.delete(document);+ if (!state || !where || where.tenantId !== state.injectedTenantPredicate) {+ return;+ }++ if (state.hadTenantId) {+ where.tenantId = state.tenantId;+ return;+ }++ const { tenantId: _tenantId, ...rest } = where;+ document.$where = Object.keys(rest).length > 0 ? rest : undefined;+}++function applyTenantWhere(document: TenantWhereDocument, tenantPredicate: unknown): void {+ const where = document.$where;+ tenantWhereStates.set(document, {+ injectedTenantPredicate: tenantPredicate,+ hadTenantId: where != null && Object.prototype.hasOwnProperty.call(where, 'tenantId'),+ tenantId: where?.tenantId,+ });+ document.$where = { ...where, tenantId: tenantPredicate };+}++/** Rolls back a plugin-owned tenant stamp when the corresponding save fails. */+function restoreTenantStamp(document: TenantSaveDocument): void {+ const state = tenantStampStates.get(document);+ tenantStampStates.delete(document);+ if (!state || document.get('tenantId') !== state.injectedTenantId) {+ return;+ }+ document.set('tenantId', state.tenantId);+ document.unmarkModified('tenantId');+}+/*** Mongoose schema plugin that enforces tenant-level data isolation.*@@ -108,7 +173,42 @@ export function applyTenantIsolation(schema: Schema): void {});schema.pre('save', function () {- stampTenantOnDocument(resolveTenantScope('Save'), this as unknown as TenantDocument);+ const scope = resolveTenantScope('Save');+ const document = this as unknown as TenantSaveDocument;+ restoreTenantWhere(document);+ const isNew = this.isNew;+ const tenantId = this.get('tenantId');+ const predicate = isNew+ ? undefined+ : tenantWritePredicate(scope, this.isModified('tenantId'), tenantId);+ stampTenantOnDocument(scope, this as unknown as TenantDocument);++ if (isNew) {+ return;+ }++ if (scope.kind === 'scoped' && !tenantId) {+ tenantStampStates.set(document, { injectedTenantId: scope.tenantId, tenantId });+ }++ /**+ * `save()` on a persisted document is filtered on `_id` alone, so the+ * stamped tenant above is never asserted. `$where` is Mongoose's public+ * hook for adding conditions to that query — its own sharding plugin uses+ * it the same way. A mismatch surfaces as `DocumentNotFoundError`.+ */+ if (predicate) {+ applyTenantWhere(document, predicate.tenantId);+ }+ });++ schema.post('save', function () {+ tenantStampStates.delete(this as unknown as TenantSaveDocument);+ });++ schema.post('save', { errorHandler: true }, function (error: Error, _document, next): void {+ restoreTenantStamp(this as unknown as TenantSaveDocument);+ next(error);});schema.pre('insertMany', function (next, docs) {diff --git a/packages/data-schemas/src/tenant/policy.spec.ts b/packages/data-schemas/src/tenant/policy.spec.tsindex d72143bcee..dadc8384ad 100644--- a/packages/data-schemas/src/tenant/policy.spec.ts+++ b/packages/data-schemas/src/tenant/policy.spec.ts@@ -7,6 +7,7 @@ import {TenantIsolationError,stampTenantOnDocument,sanitizeTenantMutation,+ tenantWritePredicate,resetTenantStrictCache,} from './policy';import { tenantStorage, SYSTEM_TENANT_ID } from '~/config/tenantContext';@@ -254,6 +255,30 @@ describe('scopeReplacement', () => {});});+describe('tenantWritePredicate', () => {+ it('matches the active tenant or an explicitly legacy value', () => {+ expect(tenantWritePredicate(SCOPED, false, undefined)).toEqual({+ tenantId: { $in: ['tenant-a', null, ''] },+ });+ });++ it('allows a modified tenantId that still names the active tenant', () => {+ expect(tenantWritePredicate(SCOPED, true, 'tenant-a')).toEqual({+ tenantId: { $in: ['tenant-a', null, ''] },+ });+ });++ it('rejects a cross-tenant tenantId modification outside system scope', () => {+ expect(() => tenantWritePredicate(SCOPED, true, 'tenant-b')).toThrow(TenantIsolationError);+ expect(() => tenantWritePredicate(UNSCOPED, true, 'tenant-a')).toThrow(TenantIsolationError);+ });++ it('yields nothing for system or unscoped saves', () => {+ expect(tenantWritePredicate(SYSTEM, true, 'tenant-b')).toBeUndefined();+ expect(tenantWritePredicate(UNSCOPED, false, undefined)).toBeUndefined();+ });+});+describe('stampTenantOnDocument', () => {it('stamps the active tenant onto a new document', () => {const document: Record<string, unknown> = { name: 'x' };diff --git a/packages/data-schemas/src/tenant/policy.ts b/packages/data-schemas/src/tenant/policy.tsindex c693ec310b..109a102be7 100644--- a/packages/data-schemas/src/tenant/policy.ts+++ b/packages/data-schemas/src/tenant/policy.ts@@ -221,6 +221,35 @@ export function scopeReplacement(return { replacement, changed: false };}+/**+ * The predicate a `save()` must carry for an already-persisted document, which+ * would otherwise be filtered on identity alone.+ *+ * The legacy alternatives make pre-tenancy rows claimable while keeping the+ * claim atomic: once one tenant stamps the row, another tenant's save no longer+ * matches. `tenantIdModified` reflects caller changes before the save hook+ * stamps a legacy row.+ */+export function tenantWritePredicate(+ scope: TenantScope,+ tenantIdModified: boolean,+ tenantId: unknown,+): { tenantId: { $in: [string, null, ''] } } | undefined {+ if (+ tenantIdModified &&+ scope.kind !== 'system' &&+ (scope.kind !== 'scoped' || tenantId !== scope.tenantId)+ ) {+ throw new TenantIsolationError(+ '[TenantIsolation] Cross-tenant tenantId mutation is not allowed',+ );+ }+ if (scope.kind !== 'scoped') {+ return undefined;+ }+ return { tenantId: { $in: [scope.tenantId, null, ''] } };+}+/*** Stamps the active tenant onto a document being inserted.*diff --git a/packages/data-schemas/src/tenant/probe.spec.ts b/packages/data-schemas/src/tenant/probe.spec.tsindex 1d66fad438..455a67d851 100644--- a/packages/data-schemas/src/tenant/probe.spec.ts+++ b/packages/data-schemas/src/tenant/probe.spec.ts@@ -444,19 +444,7 @@ describe('document-level paths reach the wire scoped', () => {expect(describeLeaks(records)).toBe('');});- /**- * KNOWN GAP, found by this probe. Saving an already-persisted document issues- * `update` filtered on `_id` alone — the tenant is stamped onto the payload but- * never asserted in the predicate. It is scoped by provenance (you can only- * fetch a document your tenant can see), so the normal flow is safe, but an- * `_id` obtained from an unscoped source — `runAsSystem`, a cached id, a- * client-supplied id — writes across tenants unguarded.- *- * Pinned here rather than fixed: closing it changes runtime behaviour and- * belongs in its own change. The assertion is written to FAIL once the- * predicate is added, so the fix cannot land without updating this test.- */- it('doc.save() on a fetched document is scoped by provenance, not by predicate', async () => {+ it('doc.save() on a fetched document asserts the tenant in its predicate', async () => {await asTenant(async () => void (await Widget.create({ name: 'fetched', parts: [] })));const records = await probe.record(() =>@@ -469,8 +457,8 @@ describe('document-level paths reach the wire scoped', () => {const updates = records.filter((record) => record.commandName === 'update');expect(updates).toHaveLength(1);- expect(updates[0].scoped).toBe(false);- expect(updates[0].predicate).toContain('_id');+ expect(updates[0].predicate).toContain('tenantId');+ expect(describeLeaks(records)).toBe('');});it('doc.updateOne()', async () => {@@ -553,3 +541,158 @@ describe('system scope', () => {expect(unscoped(records)).toHaveLength(1);});});++/**+ * The predicate added to `save()` must harden the cross-tenant case without+ * refusing writes that were always legitimate.+ */+describe('save predicate does not break legitimate writes', () => {+ it.each([+ ['missing', undefined],+ ['empty', ''],+ ])(+ 'a document with a %s tenant can be claimed by the active tenant',+ async (_label, tenantId) => {+ const created = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.create({ name: 'pre-tenancy', parts: [], tenantId }),+ );++ const widget = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(created._id),+ );+ await asTenant(async () => {+ const scopedWidget = await Widget.findById(created._id);+ expect(scopedWidget).toBeNull();+ });++ widget!.name = 'renamed';+ await asTenant(async () => widget!.save());++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(created._id).lean(),+ );+ expect(fresh!.name).toBe('renamed');+ expect(fresh!.tenantId).toBe(TENANT);+ },+ );++ it('allows only one tenant to claim a legacy document', async () => {+ const created = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.create({ name: 'legacy-race', parts: [] }),+ );+ const [first, second] = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Promise.all([Widget.findById(created._id), Widget.findById(created._id)]),+ );++ first!.name = 'claimed-a';+ await asTenant(async () => first!.save());++ second!.name = 'claimed-b';+ await expect(+ tenantStorage.run({ tenantId: 'tenant-b' }, async () => second!.save()),+ ).rejects.toThrow('No document found');++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(created._id).lean(),+ );+ expect(fresh).toMatchObject({ name: 'claimed-a', tenantId: TENANT });+ });++ it('does not trust a projected-out tenantId', async () => {+ const foreign = await tenantStorage.run({ tenantId: 'tenant-b' }, async () =>+ Widget.create({ name: 'projected-foreign', parts: [] }),+ );+ const projected = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(foreign._id).select('-tenantId'),+ );+ expect(projected!.tenantId).toBeUndefined();++ projected!.name = 'projected-stolen';+ await expect(asTenant(async () => projected!.save())).rejects.toThrow('No document found');+ expect(projected!.tenantId).toBeUndefined();++ projected!.name = 'system-recovered';+ await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () => projected!.save());++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(foreign._id).lean(),+ );+ expect(fresh).toMatchObject({ name: 'system-recovered', tenantId: 'tenant-b' });+ });++ it('rejects tenantId mutation on a persisted document', async () => {+ const widget = await asTenant(async () => Widget.create({ name: 'tenant-move', parts: [] }));++ widget.tenantId = 'tenant-b';+ widget.name = 'moved';+ await expect(asTenant(async () => widget.save())).rejects.toThrow(+ '[TenantIsolation] Cross-tenant tenantId mutation is not allowed',+ );++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(widget._id).lean(),+ );+ expect(fresh).toMatchObject({ name: 'tenant-move', tenantId: TENANT });+ });++ it('refuses to save a document belonging to another tenant', async () => {+ const foreign = await tenantStorage.run({ tenantId: 'tenant-b' }, async () =>+ Widget.create({ name: 'foreign', parts: [] }),+ );++ const smuggled = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(foreign._id),+ );++ await expect(+ asTenant(async () => {+ smuggled!.name = 'stolen';+ await smuggled!.save();+ }),+ ).rejects.toThrow('No document found');++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(foreign._id).lean(),+ );+ expect(fresh!.name).toBe('foreign');++ smuggled!.name = 'system-recovered';+ await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () => smuggled!.save());++ const recovered = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(foreign._id).lean(),+ );+ expect(recovered!.name).toBe('system-recovered');+ });++ it('leaves system-scoped saves unfiltered', async () => {+ const created = await asTenant(async () => Widget.create({ name: 'sys-target', parts: [] }));++ const widget = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(created._id),+ );+ widget!.name = 'tenant-renamed';+ await asTenant(async () => widget!.save());++ const records = await probe.record(() =>+ tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () => {+ widget!.name = 'sys-renamed';+ await widget!.save();+ }),+ );++ const updates = records.filter((record) => record.commandName === 'update');+ expect(updates).toHaveLength(1);+ expect(updates[0].predicate).not.toContain('tenantId');++ widget!.name = 'sys-renamed-again';+ await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () => {+ await widget!.save();+ });++ const fresh = await tenantStorage.run({ tenantId: SYSTEM_TENANT_ID }, async () =>+ Widget.findById(created._id).lean(),+ );+ expect(fresh!.name).toBe('sys-renamed-again');+ });+});diff --git a/packages/data-schemas/src/tenant/probe.ts b/packages/data-schemas/src/tenant/probe.tsindex b2a3ed798b..01074d6a14 100644--- a/packages/data-schemas/src/tenant/probe.ts+++ b/packages/data-schemas/src/tenant/probe.ts@@ -108,6 +108,28 @@ function pinsTenant(filter: unknown, tenantId: string): boolean {return (filter as CommandDocument).tenantId === tenantId;}+/** The exact atomic-claim predicate emitted by persisted document saves. */+function pinsTenantOrLegacy(filter: unknown, tenantId: string): boolean {+ if (filter == null || typeof filter !== 'object' || Array.isArray(filter)) {+ return false;+ }+ const condition = (filter as CommandDocument).tenantId;+ if (condition == null || typeof condition !== 'object' || Array.isArray(condition)) {+ return false;+ }+ const keys = Object.keys(condition);+ const values = (condition as CommandDocument).$in;+ return (+ keys.length === 1 &&+ keys[0] === '$in' &&+ Array.isArray(values) &&+ values.length === 3 &&+ values[0] === tenantId &&+ values[1] === null &&+ values[2] === ''+ );+}+/** A `$lookup` reads its foreign collection inside the outer command. */function lookupTargetsTenant(lookup: unknown, tenantId: string): boolean {if (lookup == null || typeof lookup !== 'object') {@@ -272,7 +294,11 @@ function isScoped(command: CommandDocument, commandName: string, tenantId: strinif (!PREDICATE_PATHS.has(commandName)) {return false;}- return predicatesOf(command, commandName).every((predicate) => pinsTenant(predicate, tenantId));+ return predicatesOf(command, commandName).every(+ (predicate) =>+ pinsTenant(predicate, tenantId) ||+ (commandName === 'update' && pinsTenantOrLegacy(predicate, tenantId)),+ );}export function attachTenantProbe(