🪸 refactor: Separate Shared-Link and Schedule Persistence (#18031)
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Vote Gate / Gate (push) Waiting to run
Codegraph E2E Votes / vote (shard 1/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 10/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 2/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 3/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 4/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 5/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 6/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 7/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 8/10) (push) Waiting to run
Codegraph E2E Votes / vote (shard 9/10) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions

Co-authored-by: Lia <lia@librechat.ai>
This commit is contained in:
lia-by-librechat[bot] 2026-11-10 15:44:13 -05:00 • committed by GitHub
parent e104e820c3
commit 0eadbc45b1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 438 additions and 231 deletions

View file

@ -1,6 +1,5 @@
const express = require('express');
const request = require('supertest');
const mongoose = require('mongoose');
const mockGetSharedLinkExpiration = jest.fn();
const mockGrantCreationPermissions = jest.fn();
@ -154,17 +153,6 @@ jest.mock('librechat-data-provider', () => {
};
});
jest.mock('mongoose', () => ({
models: {
Conversation: {
findOne: jest.fn(),
},
SharedLink: {
findOne: jest.fn(),
},
},
}));
jest.mock('~/models', () => ({
getFiles: jest.fn(),
updateFile: jest.fn(),
@ -174,6 +162,8 @@ jest.mock('~/models', () => ({
deleteSharedLink: jest.fn(),
getSharedLinks: jest.fn(),
getSharedLink: jest.fn(),
findOwnedSharedLink: jest.fn(),
findShareConversationRetention: jest.fn(),
getSharedLinkFile: jest.fn(),
backfillSharedLinkFiles: jest.fn(),
getMessages: jest.fn(),
@ -240,6 +230,8 @@ const {
getSharedMessages,
createSharedLink,
updateSharedLink,
findOwnedSharedLink,
findShareConversationRetention,
getSharedLinks,
getSharedLinkFile,
backfillSharedLinkFiles,
@ -259,10 +251,6 @@ const contentFilters = {
},
};
const lean = (value) => ({
lean: jest.fn().mockResolvedValue(value),
});
const buildApp = ({
retentionMode = RetentionMode.TEMPORARY,
user = { id: 'user-123' },
@ -799,12 +787,9 @@ describe('share routes', () => {
}),
);
const [, dependencies] = mockGetSharedLinkExpiration.mock.calls[0];
mongoose.models.Conversation.findOne.mockReturnValue(lean({ expiredAt: activeExpiration }));
findShareConversationRetention.mockResolvedValue({ expiredAt: activeExpiration });
await dependencies.getConvo('user-123', 'convo-123');
expect(mongoose.models.Conversation.findOne).toHaveBeenCalledWith(
{ conversationId: 'convo-123', user: 'user-123' },
'isTemporary expiredAt',
);
expect(findShareConversationRetention).toHaveBeenCalledWith('user-123', 'convo-123');
expect(createSharedLink).toHaveBeenCalledWith(
'user-123',
'convo-123',
@ -1068,9 +1053,7 @@ describe('share routes', () => {
});
it('passes the snapshotFiles opt-out through on update', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' });
@ -1099,9 +1082,7 @@ describe('share routes', () => {
},
});
const messages = [{ files: [{ file_id: 'file_PRIVATE-SENTINEL' }] }];
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
mockAssertConversationContentAllowed.mockImplementationOnce(() => {
throw error;
@ -1159,19 +1140,14 @@ describe('share routes', () => {
});
it('expires updated shares for retained non-temporary conversations', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' });
const response = await request(buildApp()).patch('/api/share/share-123');
expect(response.status).toBe(200);
expect(mongoose.models.SharedLink.findOne).toHaveBeenCalledWith(
{ shareId: 'share-123', user: 'user-123' },
'conversationId',
);
expect(findOwnedSharedLink).toHaveBeenCalledWith('user-123', 'share-123');
expect(mockGetSharedLinkExpiration).toHaveBeenCalledTimes(1);
expect(mockGetSharedLinkExpiration).toHaveBeenCalledWith(
expect.objectContaining({
@ -1200,9 +1176,7 @@ describe('share routes', () => {
});
it('does not re-publish content when re-scoping the grants fails', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
mockUpdateSharedLinkPermissionsExpiration.mockRejectedValueOnce(new Error('acl down'));
mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' });
@ -1216,9 +1190,7 @@ describe('share routes', () => {
});
it('rejects updated shares when the retained conversation expired', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(expiredExpiration);
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
@ -1229,9 +1201,7 @@ describe('share routes', () => {
});
it('rejects updated shares for expired conversations in all retention mode', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(expiredExpiration);
updateSharedLink.mockResolvedValue({ shareId: 'share-456' });
@ -1240,17 +1210,12 @@ describe('share routes', () => {
);
expect(response.status).toBe(404);
expect(mongoose.models.SharedLink.findOne).toHaveBeenCalledWith(
{ shareId: 'share-123', user: 'user-123' },
'conversationId',
);
expect(findOwnedSharedLink).toHaveBeenCalledWith('user-123', 'share-123');
expect(updateSharedLink).not.toHaveBeenCalled();
});
it('clears updated share expiration when the conversation is no longer retained', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(null);
mockUpdatedShare({ _id: 'link-456', shareId: 'share-456' });
@ -1282,9 +1247,7 @@ describe('share routes', () => {
});
it('preserves updated share expiration when the conversation cannot be found', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(undefined);
mockUpdatedShare({ shareId: 'share-456' });
@ -1305,9 +1268,7 @@ describe('share routes', () => {
it('clears updated share expiration when creating a new expiration throws', async () => {
const error = new Error('bad config');
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockImplementationOnce(async (_input, dependencies) => {
dependencies.logger.error('[getSharedLinkExpiration] Error creating expiration date:', error);
return null;
@ -1334,9 +1295,7 @@ describe('share routes', () => {
});
it('updates share target message while applying retention expiration', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(
lean({ _id: 'link-456', conversationId: 'convo-123' }),
);
findOwnedSharedLink.mockResolvedValue({ _id: 'link-456', conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
mockUpdatedShare({ shareId: 'share-456', targetMessageId: 'msg-456' });
@ -1375,7 +1334,7 @@ describe('share routes', () => {
});
it('maps a missing-share update domain error to not found', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(lean(null));
findOwnedSharedLink.mockResolvedValue(null);
updateSharedLink.mockRejectedValue(
Object.assign(new Error('Share not found'), { code: 'SHARE_NOT_FOUND' }),
);
@ -1387,7 +1346,7 @@ describe('share routes', () => {
});
it('returns and records a missing-tail update rejection', async () => {
mongoose.models.SharedLink.findOne.mockReturnValue(lean({ conversationId: 'convo-123' }));
findOwnedSharedLink.mockResolvedValue({ conversationId: 'convo-123' });
mockGetSharedLinkExpiration.mockResolvedValue(activeExpiration);
updateSharedLink.mockRejectedValue(
Object.assign(new Error('Target message not found'), {

View file

@ -1,4 +1,4 @@
const mongoose = require('mongoose');
const { findSharedLinkById } = require('~/models');
const express = require('express');
const {
AccessRoleIds,
@ -158,8 +158,7 @@ const rejectSharedLinkOwnerPermissionChanges = async (req, res, next) => {
}
try {
const SharedLink = mongoose.models.SharedLink;
const link = await SharedLink.findById(req.params.resourceId, 'user').lean();
const link = await findSharedLinkById(req.params.resourceId);
const ownerId = link?.user?.toString();
const touchesOwner = ownerId
? userMutations.some((principal) => principal.id?.toString() === ownerId)

View file

@ -1,5 +1,6 @@
jest.mock('~/models', () => ({
getRoleByName: jest.fn(),
findSharedLinkById: jest.fn(),
findMCPServerByObjectId: jest.fn(),
getSkillById: jest.fn(),
}));
@ -34,7 +35,6 @@ jest.mock('~/server/controllers/PermissionsController', () => ({
const express = require('express');
const request = require('supertest');
const mongoose = require('mongoose');
const {
SystemRoles,
ResourceType,
@ -49,12 +49,11 @@ const { updateResourcePermissions } = require('~/server/controllers/PermissionsC
const { hasCapability } = require('~/server/middleware/roles/capabilities');
const { canAccessResource } = require('~/server/middleware');
const accessPermissionsRouter = require('./accessPermissions');
const { getRoleByName } = require('~/models');
const { getRoleByName, findSharedLinkById } = require('~/models');
describe('Access permissions share policy', () => {
let app;
const mockSharedLinkFindById = jest.fn();
const originalSharedLinkModel = mongoose.models.SharedLink;
const mockSharedLinkFindById = findSharedLinkById;
const resourceId = '507f1f77bcf86cd799439011';
const sharePolicyCases = [
@ -135,18 +134,11 @@ describe('Access permissions share policy', () => {
};
const mockSharedLinkOwner = (ownerId = 'owner-user') => {
mockSharedLinkFindById.mockReturnValue({
lean: jest.fn().mockResolvedValue({ user: ownerId }),
});
mockSharedLinkFindById.mockResolvedValue({ user: ownerId });
};
beforeEach(() => {
jest.clearAllMocks();
if (mongoose.models.SharedLink) {
mongoose.models.SharedLink.findById = mockSharedLinkFindById;
} else {
mongoose.models.SharedLink = { findById: mockSharedLinkFindById };
}
hasCapability.mockResolvedValue(false);
app = express();
@ -158,14 +150,6 @@ describe('Access permissions share policy', () => {
app.use('/api/permissions', accessPermissionsRouter);
});
afterAll(() => {
if (originalSharedLinkModel) {
mongoose.models.SharedLink = originalSharedLinkModel;
} else {
delete mongoose.models.SharedLink;
}
});
it.each(sharePolicyCases)(
'blocks non-public $label sharing when ACL SHARE passes but role SHARE is disabled',
async ({ resourceType, permissionType, accessRoleId, middlewareOptions }) => {
@ -337,4 +321,14 @@ describe('Access permissions share policy', () => {
expect(response.status).toBe(200);
expect(updateResourcePermissions).toHaveBeenCalledTimes(1);
});
it('fails closed when the canonical owner query rejects', async () => {
allowSharedLinkSharing();
findSharedLinkById.mockRejectedValueOnce(new Error('database secret'));
const response = await request(app)
.put(`/api/permissions/${ResourceType.SHARED_LINK}/${resourceId}`)
.send({ removed: [{ type: PrincipalType.USER, id: 'owner-user' }] });
expect(response.status).toBe(500);
expect(response.body.message).toBe('Failed to validate shared link owner permissions');
expect(updateResourcePermissions).not.toHaveBeenCalled();
});
});

View file

@ -1,4 +1,3 @@
const mongoose = require('mongoose');
const express = require('express');
const {
assertModelBoundContent,
@ -43,6 +42,8 @@ const {
updateSharedLink,
getSharedLinks,
getSharedLink,
findOwnedSharedLink,
findShareConversationRetention,
getSharedLinkFile,
backfillSharedLinkFiles,
getMessages,
@ -117,13 +118,7 @@ const resolveSharedLinkExpiration = (req, conversationId) =>
getSharedLinkExpiration(
{ req, conversationId },
{
getConvo: async (userId, sourceConversationId) => {
const Conversation = mongoose.models.Conversation;
return Conversation.findOne(
{ conversationId: sourceConversationId, user: userId },
'isTemporary expiredAt',
).lean();
},
getConvo: findShareConversationRetention,
createExpirationDate: createChatExpirationDate,
logger,
},
@ -720,11 +715,7 @@ router.patch(
}
let expiredAt;
const SharedLink = mongoose.models.SharedLink;
const existing = await SharedLink.findOne(
{ shareId: req.params.shareId, user: req.user.id },
'conversationId',
).lean();
const existing = await findOwnedSharedLink(req.user.id, req.params.shareId);
if (existing?.conversationId) {
expiredAt = await resolveSharedLinkExpiration(req, existing.conversationId);
}

View file

@ -1,15 +1,13 @@
const mongoose = require('mongoose');
const { createResolveAgentFireAccess } = require('@librechat/api');
const { checkPermission } = require('~/server/services/PermissionService');
const { hasCapability } = require('~/server/middleware/roles/capabilities');
const { getRoleByName } = require('~/models');
const { getRoleByName, findAgentIdentity } = require('~/models');
// Thin wiring over the TypeScript implementation in packages/api: inject the
// api-layer lookups (agent id, role, capability, resource ACL); the authorization
// logic itself lives in @librechat/api so it stays type-checked and in-boundary.
const resolveAgentFireAccess = createResolveAgentFireAccess({
findAgentObjectId: (agentId) =>
mongoose.models.Agent.findOne({ id: agentId }).select('_id').lean(),
findAgentObjectId: findAgentIdentity,
getRoleByName,
hasCapability,
checkPermission,

View file

@ -10,7 +10,6 @@ function getService() {
if (service != null) {
return service;
}
const mongoose = require('mongoose');
const { createSchedulesService } = require('@librechat/api');
const { getAppConfig } = require('~/server/services/Config/app');
const {
@ -25,21 +24,12 @@ function getService() {
preflightMCP: require('./mcp'),
methods,
getAppConfig,
findUserById: (userId) =>
mongoose.models.User.findById(userId).select('_id tenantId role termsAccepted').lean(),
findUserById: (userId) => methods.findScheduleOwner(userId.toString()),
findBalance: (userId, options) =>
methods.findBalanceByUser(userId, { includeReservedCredits: true, ...options }),
upsertBalance: (userId, { set, setOnInsert }) =>
methods.upsertBalanceFields(userId, set ?? {}, setOnInsert ?? {}),
// Compare-and-set: only initialize an existing record while its credit is still null.
// No upsert — a CAS miss must re-read the winner, not insert a fresh balance. `null`
// in the filter also matches a legacy record whose `tokenCredits` field is absent.
initializeNullBalance: (userId, { tokenCredits, sync }) =>
mongoose.models.Balance.findOneAndUpdate(
{ user: userId, tokenCredits: null },
{ $set: { tokenCredits, ...(sync && Object.keys(sync).length > 0 ? sync : {}) } },
{ new: true, sort: { _id: 1 } },
).lean(),
initializeNullBalance: methods.initializeNullBalance,
enqueueAgentTrigger,
// Reconciliation reads the durable delivery to tell a still-live admission (a
// deferred Retry-After) or a dead-letter apart from a genuinely orphaned run.

View file

@ -6,12 +6,15 @@ const mockCreateSchedulesService = jest.fn(() => ({
jest.mock('@librechat/api', () => ({
createSchedulesService: (...args) => mockCreateSchedulesService(...args),
}));
jest.mock('mongoose', () => ({ models: {} }));
jest.mock('~/server/services/Config/app', () => ({ getAppConfig: jest.fn() }));
jest.mock('~/server/services/Agents/triggers', () => ({ enqueueAgentTrigger: jest.fn() }));
jest.mock('./mcp', () => jest.fn());
jest.mock('./access', () => ({ resolveAgentFireAccess: jest.fn() }));
jest.mock('~/models', () => ({ isAgentTriggerPrincipalActive: jest.fn() }));
jest.mock('~/models', () => ({
isAgentTriggerPrincipalActive: jest.fn(),
findScheduleOwner: jest.fn(),
initializeNullBalance: jest.fn(),
}));
const { recordExpiredScheduleApproval } = require('./index');
@ -62,11 +65,9 @@ describe('recordExpiredScheduleApproval', () => {
describe('schedule owner lookup', () => {
it('selects the terms acceptance flag the fire-time terms check reads', async () => {
const mongoose = require('mongoose');
const lean = jest.fn().mockResolvedValue({ _id: 'user-1', termsAccepted: false });
const select = jest.fn(() => ({ lean }));
const findById = jest.fn(() => ({ select }));
mongoose.models.User = { findById };
const methods = require('~/models');
const owner = { _id: 'user-1', termsAccepted: false };
methods.findScheduleOwner.mockResolvedValue(owner);
mockRecordScheduleOutcome.mockResolvedValue(true);
let facade;
jest.isolateModules(() => {
@ -80,11 +81,10 @@ describe('schedule owner lookup', () => {
scheduledFor: '2026-08-17T12:00:00.000Z',
});
const { findUserById } = mockCreateSchedulesService.mock.calls.at(-1)[0];
await findUserById('user-1');
expect(findById).toHaveBeenCalledWith('user-1');
expect(select.mock.calls[0][0].split(' ')).toEqual(
expect.arrayContaining(['_id', 'tenantId', 'role', 'termsAccepted']),
await expect(findUserById('user-1')).resolves.toEqual(owner);
expect(methods.findScheduleOwner).toHaveBeenCalledWith('user-1');
expect(mockCreateSchedulesService.mock.calls.at(-1)[0].initializeNullBalance).toBe(
methods.initializeNullBalance,
);
});
});