mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 13:00:55 +00:00
🪸 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
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:
parent
e104e820c3
commit
0eadbc45b1
20 changed files with 438 additions and 231 deletions
|
|
@ -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'), {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,14 +6,13 @@ import {
|
|||
PermissionTypes,
|
||||
} from 'librechat-data-provider';
|
||||
import type { SystemCapability } from '@librechat/data-schemas';
|
||||
import type { Types } from 'mongoose';
|
||||
import type { ScheduleUserContext } from './types';
|
||||
|
||||
type AgentAccess = 'ok' | 'missing' | 'forbidden';
|
||||
|
||||
export interface AgentFireAccessDeps {
|
||||
/** Resolves an agent's internal `_id` by its custom id, or null when it doesn't exist. */
|
||||
findAgentObjectId: (agentId: string) => Promise<{ _id: Types.ObjectId } | null>;
|
||||
findAgentObjectId: (agentId: string) => Promise<{ _id: string } | null>;
|
||||
/** Loads a role's permission map by name. */
|
||||
getRoleByName: (
|
||||
role?: string,
|
||||
|
|
@ -25,7 +24,7 @@ export interface AgentFireAccessDeps {
|
|||
userId: string;
|
||||
role?: string;
|
||||
resourceType: ResourceType;
|
||||
resourceId: Types.ObjectId;
|
||||
resourceId: string;
|
||||
requiredPermission: PermissionBits;
|
||||
}) => Promise<boolean>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -135,7 +135,7 @@ it('denies an owner/tenant mismatch and cancellation before resolving resources'
|
|||
it('honors capability-only root access without bypassing descendant VIEW checks', async () => {
|
||||
const { deps, resolve } = setup();
|
||||
const rootAccess = createResolveAgentFireAccess({
|
||||
findAgentObjectId: async () => ({ _id: new Types.ObjectId() }),
|
||||
findAgentObjectId: async () => ({ _id: new Types.ObjectId().toString() }),
|
||||
getRoleByName: async () => ({
|
||||
permissions: { [PermissionTypes.AGENTS]: { [Permissions.USE]: true } },
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -167,7 +167,7 @@ export interface SchedulesServiceDeps {
|
|||
};
|
||||
getAppConfig: (options?: GetAppConfigOptions) => Promise<AppConfig | undefined>;
|
||||
findUserById: (userId: string | Types.ObjectId) => Promise<{
|
||||
_id: Types.ObjectId;
|
||||
_id: string | Types.ObjectId;
|
||||
tenantId?: string;
|
||||
role?: string;
|
||||
termsAccepted?: boolean;
|
||||
|
|
|
|||
|
|
@ -1,28 +1,11 @@
|
|||
import { ResourceType, PermissionBits } from 'librechat-data-provider';
|
||||
import {
|
||||
getTenantId,
|
||||
runAsSystem,
|
||||
tenantStorage,
|
||||
activeExpirationFilter,
|
||||
} from '@librechat/data-schemas';
|
||||
import { getTenantId, runAsSystem, tenantStorage, createMethods } from '@librechat/data-schemas';
|
||||
import type { IUser, ShareMethods } from '@librechat/data-schemas';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
import type { IUser } from '@librechat/data-schemas';
|
||||
import type { Types, Model } from 'mongoose';
|
||||
import { AccessControlService } from '~/acl/accessControlService';
|
||||
import { autoMigrateLegacyLink } from './service';
|
||||
import { isEnabled } from '~/utils';
|
||||
|
||||
interface RawSharedLink {
|
||||
_id?: Types.ObjectId;
|
||||
conversationId: string;
|
||||
title?: string;
|
||||
user?: string;
|
||||
shareId?: string;
|
||||
tenantId?: string;
|
||||
isPublic?: boolean;
|
||||
expiredAt?: Date;
|
||||
}
|
||||
|
||||
interface SharedLinkAccessRequest extends Request {
|
||||
shareResourceId?: string;
|
||||
shareTenantId?: string;
|
||||
|
|
@ -33,6 +16,7 @@ interface SharedLinkAccessRequest extends Request {
|
|||
export interface SharedLinkAccessDeps {
|
||||
mongoose: typeof import('mongoose');
|
||||
aclService?: AccessControlService;
|
||||
findActiveSharedLink?: ShareMethods['findActiveSharedLink'];
|
||||
}
|
||||
|
||||
function isAutoMigrateEnabled(): boolean {
|
||||
|
|
@ -44,6 +28,7 @@ function isAutoMigrateEnabled(): boolean {
|
|||
export function createSharedLinkAccessMiddleware(deps: SharedLinkAccessDeps) {
|
||||
const { mongoose: mg } = deps;
|
||||
const aclService = deps.aclService ?? new AccessControlService(mg);
|
||||
const findActiveSharedLink = deps.findActiveSharedLink ?? createMethods(mg).findActiveSharedLink;
|
||||
|
||||
async function hasPublicViewPermission(resourceId: string): Promise<boolean> {
|
||||
return aclService.hasPublicAccess({
|
||||
|
|
@ -64,12 +49,7 @@ export function createSharedLinkAccessMiddleware(deps: SharedLinkAccessDeps) {
|
|||
}
|
||||
|
||||
const viewerTenantId = getTenantId();
|
||||
const SharedLink = mg.models.SharedLink as Model<RawSharedLink>;
|
||||
const findShare = async () =>
|
||||
(await SharedLink.findOne({
|
||||
shareId,
|
||||
...activeExpirationFilter<RawSharedLink>(),
|
||||
}).lean()) as RawSharedLink | null;
|
||||
const findShare = () => findActiveSharedLink(shareId);
|
||||
// Resolve by the (globally unique, secret) shareId under the viewer's tenant
|
||||
// first, then fall back to a system-wide lookup so a share owned by another
|
||||
// tenant — e.g. a public link opened by an authenticated user from a
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { MongoMemoryServer } from 'mongodb-memory-server';
|
|||
import { createModels, createMethods } from '@librechat/data-schemas';
|
||||
import { PrincipalType, AccessRoleIds } from 'librechat-data-provider';
|
||||
import type { IAclEntry, ISharedLink } from '@librechat/data-schemas';
|
||||
import { AccessControlService } from '~/acl/accessControlService';
|
||||
import {
|
||||
autoMigrateLegacyLink,
|
||||
grantCreationPermissions,
|
||||
|
|
@ -408,3 +409,49 @@ describe('deleteAllSharedLinksWithCleanup', () => {
|
|||
expect(await AclEntry.countDocuments({ resourceId: link._id })).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('persistence failures', () => {
|
||||
test.each([1, 2])(
|
||||
'compensates link and ACL after grant %s partially writes then fails',
|
||||
async (failingGrant) => {
|
||||
const link = await createTestLink();
|
||||
const original = AccessControlService.prototype.grantPermission;
|
||||
let calls = 0;
|
||||
const grant = jest
|
||||
.spyOn(AccessControlService.prototype, 'grantPermission')
|
||||
.mockImplementation(async function (this: AccessControlService, params) {
|
||||
const result = await original.call(this, params);
|
||||
if (++calls === failingGrant) {
|
||||
throw new Error('grant failed');
|
||||
}
|
||||
return result;
|
||||
});
|
||||
try {
|
||||
await expect(grantCreationPermissions(link._id, userId, true)).rejects.toThrow(
|
||||
'grant failed',
|
||||
);
|
||||
expect(await SharedLink.findById(link._id)).toBeNull();
|
||||
expect(await AclEntry.countDocuments({ resourceId: link._id })).toBe(0);
|
||||
} finally {
|
||||
grant.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('expiration update failures reject instead of reporting success', async () => {
|
||||
const link = await createTestLink();
|
||||
const update = jest.spyOn(AclEntry, 'updateMany').mockRejectedValueOnce(new Error('acl down'));
|
||||
await expect(updateSharedLinkPermissionsExpiration(link._id, null)).rejects.toThrow('acl down');
|
||||
update.mockRestore();
|
||||
});
|
||||
|
||||
test('ordinary deletion remains successful when ACL cleanup fails', async () => {
|
||||
const link = await createTestLink();
|
||||
const cleanup = jest.spyOn(AclEntry, 'deleteMany').mockRejectedValueOnce(new Error('acl down'));
|
||||
await expect(deleteSharedLinkWithCleanup(userId, link.shareId!)).resolves.toMatchObject({
|
||||
success: true,
|
||||
});
|
||||
expect(await SharedLink.findById(link._id)).toBeNull();
|
||||
cleanup.mockRestore();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,15 +1,20 @@
|
|||
import mongoose from 'mongoose';
|
||||
import { logger } from '@librechat/data-schemas';
|
||||
import { logger, createMethods } from '@librechat/data-schemas';
|
||||
import {
|
||||
PrincipalType,
|
||||
ResourceType,
|
||||
AccessRoleIds,
|
||||
PermissionBits,
|
||||
} from 'librechat-data-provider';
|
||||
import type { Model, Types, DeleteResult, UpdateQuery } from 'mongoose';
|
||||
import type { IAclEntry, ISharedLink } from '@librechat/data-schemas';
|
||||
import type { AllMethods } from '@librechat/data-schemas';
|
||||
import type { Types } from 'mongoose';
|
||||
import { AccessControlService } from '~/acl/accessControlService';
|
||||
|
||||
let _methods: AllMethods | undefined;
|
||||
function getMethods(): AllMethods {
|
||||
return (_methods ??= createMethods(mongoose));
|
||||
}
|
||||
|
||||
let _aclService: AccessControlService | null = null;
|
||||
function getAclService(): AccessControlService {
|
||||
if (!_aclService) {
|
||||
|
|
@ -19,7 +24,7 @@ function getAclService(): AccessControlService {
|
|||
}
|
||||
|
||||
interface RawSharedLink {
|
||||
_id?: Types.ObjectId;
|
||||
_id?: string | Types.ObjectId;
|
||||
conversationId: string;
|
||||
title?: string;
|
||||
user?: string;
|
||||
|
|
@ -110,9 +115,7 @@ export async function autoMigrateLegacyLink(share: RawSharedLink): Promise<void>
|
|||
return;
|
||||
}
|
||||
|
||||
await mongoose.connection
|
||||
.db!.collection('sharedlinks')
|
||||
.updateOne({ _id: shareId }, { $unset: { isPublic: 1 } });
|
||||
await getMethods().clearSharedLinkLegacyVisibility(resourceId);
|
||||
|
||||
logger.info('[autoMigrateLegacyLink] Migrated legacy shared link', {
|
||||
shareId: share.shareId,
|
||||
|
|
@ -145,7 +148,10 @@ export async function grantCreationPermissions(
|
|||
resourceId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
await mongoose.models.SharedLink.deleteOne({ _id: sharedLinkId });
|
||||
await Promise.all([
|
||||
getMethods().deleteSharedLinkById(resourceId),
|
||||
cleanupSharedLinkPermissions(resourceId),
|
||||
]);
|
||||
throw err;
|
||||
}
|
||||
|
||||
|
|
@ -166,7 +172,7 @@ export async function grantCreationPermissions(
|
|||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
await Promise.all([
|
||||
mongoose.models.SharedLink.deleteOne({ _id: sharedLinkId }),
|
||||
getMethods().deleteSharedLinkById(resourceId),
|
||||
getAclService().removeAllPermissions({
|
||||
resourceType: ResourceType.SHARED_LINK,
|
||||
resourceId,
|
||||
|
|
@ -181,8 +187,7 @@ export async function ensureLinkPermissions(
|
|||
sharedLinkId: string | Types.ObjectId,
|
||||
userId: string,
|
||||
): Promise<void> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<ISharedLink>;
|
||||
const rawDoc = await SharedLink.findById(sharedLinkId).lean();
|
||||
const rawDoc = await getMethods().findSharedLinkById(sharedLinkId.toString());
|
||||
|
||||
if (!rawDoc) {
|
||||
return;
|
||||
|
|
@ -192,7 +197,7 @@ export async function ensureLinkPermissions(
|
|||
* back through the migration: the owner grant alone does not mean the public one was
|
||||
* ever created. `autoMigrateLegacyLink` skips the grants that are already in place. */
|
||||
if ('isPublic' in rawDoc) {
|
||||
await autoMigrateLegacyLink(rawDoc as Parameters<typeof autoMigrateLegacyLink>[0]);
|
||||
await autoMigrateLegacyLink(rawDoc);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -231,117 +236,79 @@ export async function ensureLinkPermissions(
|
|||
|
||||
export async function cleanupSharedLinkPermissions(
|
||||
resourceId: string | Types.ObjectId,
|
||||
): Promise<DeleteResult> {
|
||||
return getAclService().removeAllPermissions({
|
||||
resourceType: ResourceType.SHARED_LINK,
|
||||
resourceId,
|
||||
});
|
||||
): Promise<{ acknowledged: boolean; deletedCount: number }> {
|
||||
return getMethods().deleteSharedLinkAclEntries([resourceId.toString()]);
|
||||
}
|
||||
|
||||
export async function cleanupBulkSharedLinkPermissions(
|
||||
resourceIds: (string | Types.ObjectId)[],
|
||||
): Promise<DeleteResult> {
|
||||
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
|
||||
return AclEntry.deleteMany({
|
||||
resourceType: ResourceType.SHARED_LINK,
|
||||
resourceId: { $in: resourceIds },
|
||||
});
|
||||
): Promise<{ acknowledged: boolean; deletedCount: number }> {
|
||||
return getMethods().deleteSharedLinkAclEntries(resourceIds.map((id) => id.toString()));
|
||||
}
|
||||
|
||||
export async function updateSharedLinkPermissionsExpiration(
|
||||
resourceId: string | Types.ObjectId,
|
||||
expiredAt: Date | null,
|
||||
): Promise<void> {
|
||||
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
|
||||
const update: UpdateQuery<IAclEntry> =
|
||||
expiredAt instanceof Date ? { $set: { expiredAt } } : { $unset: { expiredAt: 1 } };
|
||||
|
||||
await AclEntry.updateMany(
|
||||
{
|
||||
resourceType: ResourceType.SHARED_LINK,
|
||||
resourceId,
|
||||
},
|
||||
update,
|
||||
);
|
||||
await getMethods().updateSharedLinkAclExpiration(resourceId.toString(), expiredAt);
|
||||
}
|
||||
|
||||
export async function deleteSharedLinkWithCleanup(
|
||||
user: string,
|
||||
shareId: string,
|
||||
): Promise<{ _id?: string; success: boolean; shareId: string; message: string } | null> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<ISharedLink>;
|
||||
const result = await SharedLink.findOneAndDelete({ shareId, user }).lean();
|
||||
|
||||
const result = await getMethods().deleteSharedLink(user, shareId);
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resourceId = result._id;
|
||||
if (resourceId) {
|
||||
cleanupSharedLinkPermissions(resourceId).catch((err) => {
|
||||
if (result._id) {
|
||||
cleanupSharedLinkPermissions(result._id).catch((err) => {
|
||||
logger.error('[deleteSharedLinkWithCleanup] ACL cleanup failed', {
|
||||
shareId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
_id: resourceId?.toString(),
|
||||
success: true,
|
||||
shareId,
|
||||
message: 'Share deleted successfully',
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteConvoSharedLinksWithCleanup(
|
||||
user: string,
|
||||
conversationId: string,
|
||||
): Promise<{ message: string; deletedCount: number }> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<ISharedLink>;
|
||||
const links = await SharedLink.find({ user, conversationId }).select('_id').lean();
|
||||
const ids = links.map((l) => l._id);
|
||||
const result = await SharedLink.deleteMany({ user, conversationId });
|
||||
|
||||
if (ids.length > 0) {
|
||||
cleanupBulkSharedLinkPermissions(ids).catch((err) => {
|
||||
const { deletedIds, ...result } = await getMethods().deleteConvoSharedLink(user, conversationId);
|
||||
if (deletedIds.length > 0) {
|
||||
cleanupBulkSharedLinkPermissions(deletedIds).catch((err) => {
|
||||
logger.error('[deleteConvoSharedLinksWithCleanup] ACL cleanup failed', {
|
||||
conversationId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
message: 'Shared links deleted successfully',
|
||||
deletedCount: result.deletedCount,
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function deleteAllSharedLinksWithCleanup(
|
||||
user: string,
|
||||
options: { awaitCleanup?: boolean } = {},
|
||||
): Promise<{ message: string; deletedCount: number }> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<ISharedLink>;
|
||||
const links = await SharedLink.find({ user }).select('_id').lean();
|
||||
const ids = links.map((l) => l._id);
|
||||
if (options.awaitCleanup && ids.length > 0) {
|
||||
/** The links identify the ACL resources, so they must outlive a failed cleanup for a retry. */
|
||||
await cleanupBulkSharedLinkPermissions(ids);
|
||||
}
|
||||
const result = await SharedLink.deleteMany({ user });
|
||||
|
||||
if (!options.awaitCleanup && ids.length > 0) {
|
||||
cleanupBulkSharedLinkPermissions(ids).catch((err) => {
|
||||
const { deletedIds, ...result } = await getMethods().deleteAllSharedLinks(
|
||||
user,
|
||||
options.awaitCleanup
|
||||
? async (ids) => {
|
||||
if (ids.length > 0) {
|
||||
await cleanupBulkSharedLinkPermissions(ids);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
if (!options.awaitCleanup && deletedIds.length > 0) {
|
||||
cleanupBulkSharedLinkPermissions(deletedIds).catch((err) => {
|
||||
logger.error('[deleteAllSharedLinksWithCleanup] ACL cleanup failed', {
|
||||
user,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
message: 'All shared links deleted successfully',
|
||||
deletedCount: result.deletedCount,
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Types } from 'mongoose';
|
||||
import {
|
||||
ResourceType,
|
||||
PrincipalType,
|
||||
PrincipalModel,
|
||||
PermissionBits,
|
||||
|
|
@ -131,6 +132,8 @@ export const OWNER_ACL_PERMISSION_BIT_SUPERSETS: readonly number[] =
|
|||
const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
|
||||
|
||||
export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
|
||||
deleteSharedLinkAclEntries: (resourceIds: string[]) => Promise<DeleteResult>;
|
||||
updateSharedLinkAclExpiration: (resourceId: string, expiredAt: Date | null) => Promise<void>;
|
||||
findEntriesByResource: (
|
||||
resourceType: string,
|
||||
resourceId: string | Types.ObjectId,
|
||||
|
|
@ -907,7 +910,28 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
|
|||
return ownedIds.filter((id) => !multiOwnerIds.has(id.toString()));
|
||||
}
|
||||
|
||||
async function deleteSharedLinkAclEntries(resourceIds: string[]): Promise<DeleteResult> {
|
||||
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
|
||||
return AclEntry.deleteMany({
|
||||
resourceType: ResourceType.SHARED_LINK,
|
||||
resourceId: { $in: resourceIds },
|
||||
});
|
||||
}
|
||||
|
||||
async function updateSharedLinkAclExpiration(
|
||||
resourceId: string,
|
||||
expiredAt: Date | null,
|
||||
): Promise<void> {
|
||||
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
|
||||
await AclEntry.updateMany(
|
||||
{ resourceType: ResourceType.SHARED_LINK, resourceId },
|
||||
expiredAt instanceof Date ? { $set: { expiredAt } } : { $unset: { expiredAt: 1 } },
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
deleteSharedLinkAclEntries,
|
||||
updateSharedLinkAclExpiration,
|
||||
findEntriesByResource,
|
||||
findEntriesByPrincipalsAndResource,
|
||||
hasPermission,
|
||||
|
|
|
|||
69
packages/data-schemas/src/methods/admission.spec.ts
Normal file
69
packages/data-schemas/src/methods/admission.spec.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import mongoose from 'mongoose';
|
||||
import { MongoMemoryServer } from 'mongodb-memory-server';
|
||||
import { createModels } from '~/models';
|
||||
import { createMethods } from './index';
|
||||
|
||||
let mongo: MongoMemoryServer;
|
||||
let methods: ReturnType<typeof createMethods>;
|
||||
beforeAll(async () => {
|
||||
mongo = await MongoMemoryServer.create();
|
||||
await mongoose.connect(mongo.getUri());
|
||||
createModels(mongoose);
|
||||
methods = createMethods(mongoose);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await mongoose.disconnect();
|
||||
await mongo.stop();
|
||||
});
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
['User', 'Agent', 'SharedLink'].map((name) => mongoose.models[name].deleteMany({})),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns only live admission owner fields with a plain identity', async () => {
|
||||
const _id = new mongoose.Types.ObjectId();
|
||||
await mongoose.models.User.collection.insertOne({
|
||||
_id,
|
||||
role: 'USER',
|
||||
termsAccepted: false,
|
||||
email: 'private@example.test',
|
||||
});
|
||||
expect(await methods.findScheduleOwner(_id.toString())).toEqual({
|
||||
_id: _id.toString(),
|
||||
role: 'USER',
|
||||
termsAccepted: false,
|
||||
});
|
||||
expect(await methods.findScheduleOwner(new mongoose.Types.ObjectId().toString())).toBeNull();
|
||||
});
|
||||
|
||||
it('returns an agent identity without leaking its definition and propagates query rejection', async () => {
|
||||
const _id = new mongoose.Types.ObjectId();
|
||||
await mongoose.models.Agent.collection.insertOne({ _id, id: 'agent', instructions: 'private' });
|
||||
expect(await methods.findAgentIdentity('agent')).toEqual({ _id: _id.toString() });
|
||||
expect(await methods.findAgentIdentity('missing')).toBeNull();
|
||||
const failure = jest.spyOn(mongoose.models.Agent, 'findOne').mockImplementationOnce(() => {
|
||||
throw new Error('query failed');
|
||||
});
|
||||
await expect(methods.findAgentIdentity('agent')).rejects.toThrow('query failed');
|
||||
failure.mockRestore();
|
||||
});
|
||||
|
||||
it('discovers every user link before awaited cleanup, retaining rows when cleanup rejects', async () => {
|
||||
const user = new mongoose.Types.ObjectId().toString();
|
||||
const rows = await mongoose.models.SharedLink.create([
|
||||
{ user, conversationId: 'one', shareId: 'one', messages: [], expiredAt: new Date(0) },
|
||||
{ user, conversationId: 'two', shareId: 'two', messages: [] },
|
||||
]);
|
||||
const ids = rows.map((row) => row._id.toString()).sort();
|
||||
const cleanup = jest.fn(async (found: string[]) => {
|
||||
expect(found.sort()).toEqual(ids);
|
||||
expect(await mongoose.models.SharedLink.countDocuments({ user })).toBe(2);
|
||||
throw new Error('cleanup failed');
|
||||
});
|
||||
await expect(methods.deleteAllSharedLinks(user, cleanup)).rejects.toThrow('cleanup failed');
|
||||
expect(await mongoose.models.SharedLink.countDocuments({ user })).toBe(2);
|
||||
expect(await methods.findActiveSharedLink('one')).toBeNull();
|
||||
expect((await methods.findActiveSharedLink('two'))?._id).toBe(rows[1]._id.toString());
|
||||
expect((await methods.deleteAllSharedLinks(user)).deletedIds.sort()).toEqual(ids);
|
||||
});
|
||||
|
|
@ -1077,6 +1077,7 @@ export function createAgentMethods(
|
|||
mongoose: typeof import('mongoose'),
|
||||
deps: AgentDeps,
|
||||
): {
|
||||
findAgentIdentity: (agentId: string) => Promise<{ _id: string } | null>;
|
||||
getAgent: GetAgent;
|
||||
getAgentName: (id: string, tenantId?: string) => Promise<string | undefined>;
|
||||
getAgentVersions: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent['versions'] | null>;
|
||||
|
|
@ -2836,7 +2837,14 @@ export function createAgentMethods(
|
|||
await evictAuthUserDocsForUsers(deps.getCache, userIds);
|
||||
}
|
||||
|
||||
async function findAgentIdentity(agentId: string): Promise<{ _id: string } | null> {
|
||||
const Agent = mongoose.models.Agent as Model<IAgent>;
|
||||
const agent = await Agent.findOne({ id: agentId }).select('_id').lean();
|
||||
return agent ? { _id: agent._id.toString() } : null;
|
||||
}
|
||||
|
||||
return {
|
||||
findAgentIdentity,
|
||||
getAgent,
|
||||
getAgentName,
|
||||
getAgentVersions,
|
||||
|
|
|
|||
|
|
@ -898,8 +898,27 @@ function getMessagesUpToTarget(messages: t.IMessage[], targetMessageId: string):
|
|||
return Array.from(results);
|
||||
}
|
||||
|
||||
export interface SharedLinkAccessRecord {
|
||||
_id: string;
|
||||
conversationId: string;
|
||||
user?: string;
|
||||
shareId?: string;
|
||||
tenantId?: string;
|
||||
isPublic?: boolean;
|
||||
expiredAt?: Date;
|
||||
}
|
||||
|
||||
/** Factory function that takes mongoose instance and returns the methods */
|
||||
export function createShareMethods(mongoose: typeof import('mongoose')): {
|
||||
findShareConversationRetention: (
|
||||
user: string,
|
||||
conversationId: string,
|
||||
) => Promise<{ isTemporary?: boolean; expiredAt?: Date } | null>;
|
||||
findActiveSharedLink: (shareId: string) => Promise<SharedLinkAccessRecord | null>;
|
||||
findSharedLinkById: (resourceId: string) => Promise<SharedLinkAccessRecord | null>;
|
||||
findOwnedSharedLink: (user: string, shareId: string) => Promise<SharedLinkAccessRecord | null>;
|
||||
clearSharedLinkLegacyVisibility: (resourceId: string) => Promise<void>;
|
||||
deleteSharedLinkById: (resourceId: string) => Promise<void>;
|
||||
getSharedLink: (user: string, conversationId: string) => Promise<t.GetShareLinkResult>;
|
||||
getSharedLinks: (
|
||||
user: string,
|
||||
|
|
@ -942,12 +961,80 @@ export function createShareMethods(mongoose: typeof import('mongoose')): {
|
|||
) => Promise<t.SharedFileSnapshot | t.SharedFileSnapshot[] | null>;
|
||||
deleteAllSharedLinks: (
|
||||
user: string,
|
||||
beforeDelete?: (resourceIds: string[]) => Promise<void>,
|
||||
) => Promise<t.DeleteAllSharesResult & { deletedIds: string[] }>;
|
||||
deleteConvoSharedLink: (
|
||||
user: string,
|
||||
conversationId: string,
|
||||
) => Promise<t.DeleteAllSharesResult & { deletedIds: string[] }>;
|
||||
} {
|
||||
function accessRecord(share: t.ISharedLink | null): SharedLinkAccessRecord | null {
|
||||
if (!share?._id) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
_id: share._id.toString(),
|
||||
conversationId: share.conversationId,
|
||||
user: share.user?.toString(),
|
||||
shareId: share.shareId,
|
||||
tenantId: share.tenantId,
|
||||
expiredAt: share.expiredAt,
|
||||
...('isPublic' in share
|
||||
? { isPublic: (share as t.ISharedLink & { isPublic?: boolean }).isPublic }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function findShareConversationRetention(
|
||||
user: string,
|
||||
conversationId: string,
|
||||
): Promise<{ isTemporary?: boolean; expiredAt?: Date } | null> {
|
||||
const Conversation = mongoose.models.Conversation as Model<t.IConversation>;
|
||||
return Conversation.findOne({ conversationId, user })
|
||||
.select('isTemporary expiredAt -_id')
|
||||
.lean();
|
||||
}
|
||||
|
||||
async function findActiveSharedLink(shareId: string): Promise<SharedLinkAccessRecord | null> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<t.ISharedLink>;
|
||||
return accessRecord(
|
||||
await SharedLink.findOne({ shareId, ...activeExpirationFilter<t.ISharedLink>() })
|
||||
.select('_id conversationId user shareId tenantId expiredAt isPublic')
|
||||
.lean(),
|
||||
);
|
||||
}
|
||||
|
||||
async function findSharedLinkById(resourceId: string): Promise<SharedLinkAccessRecord | null> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<t.ISharedLink>;
|
||||
return accessRecord(
|
||||
await SharedLink.findById(resourceId)
|
||||
.select('_id conversationId user shareId tenantId expiredAt isPublic')
|
||||
.lean(),
|
||||
);
|
||||
}
|
||||
|
||||
async function findOwnedSharedLink(
|
||||
user: string,
|
||||
shareId: string,
|
||||
): Promise<SharedLinkAccessRecord | null> {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<t.ISharedLink>;
|
||||
return accessRecord(
|
||||
await SharedLink.findOne({ user, shareId })
|
||||
.select('_id conversationId user tenantId expiredAt')
|
||||
.lean(),
|
||||
);
|
||||
}
|
||||
|
||||
async function clearSharedLinkLegacyVisibility(resourceId: string): Promise<void> {
|
||||
await mongoose.connection
|
||||
.db!.collection('sharedlinks')
|
||||
.updateOne({ _id: new Types.ObjectId(resourceId) }, { $unset: { isPublic: 1 } });
|
||||
}
|
||||
|
||||
async function deleteSharedLinkById(resourceId: string): Promise<void> {
|
||||
await mongoose.models.SharedLink.deleteOne({ _id: resourceId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get shared messages for a share link
|
||||
*/
|
||||
|
|
@ -1203,11 +1290,19 @@ export function createShareMethods(mongoose: typeof import('mongoose')): {
|
|||
*/
|
||||
async function deleteAllSharedLinks(
|
||||
user: string,
|
||||
beforeDelete?: (resourceIds: string[]) => Promise<void>,
|
||||
): Promise<t.DeleteAllSharesResult & { deletedIds: string[] }> {
|
||||
let cleanupFailed = false;
|
||||
try {
|
||||
const SharedLink = mongoose.models.SharedLink as Model<t.ISharedLink>;
|
||||
const links = await SharedLink.find({ user }).select('_id').lean();
|
||||
const ids = links.map((l) => l._id.toString());
|
||||
try {
|
||||
await beforeDelete?.(ids);
|
||||
} catch (error) {
|
||||
cleanupFailed = true;
|
||||
throw error;
|
||||
}
|
||||
const result = await SharedLink.deleteMany({ user });
|
||||
return {
|
||||
message: 'All shared links deleted successfully',
|
||||
|
|
@ -1215,6 +1310,9 @@ export function createShareMethods(mongoose: typeof import('mongoose')): {
|
|||
deletedIds: ids,
|
||||
};
|
||||
} catch (error) {
|
||||
if (cleanupFailed) {
|
||||
throw error;
|
||||
}
|
||||
logger.error('[deleteAllSharedLinks] Error deleting shared links', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
user,
|
||||
|
|
@ -1668,6 +1766,12 @@ export function createShareMethods(mongoose: typeof import('mongoose')): {
|
|||
|
||||
// Return all methods
|
||||
return {
|
||||
findShareConversationRetention,
|
||||
findActiveSharedLink,
|
||||
findSharedLinkById,
|
||||
findOwnedSharedLink,
|
||||
clearSharedLinkLegacyVisibility,
|
||||
deleteSharedLinkById,
|
||||
getSharedLink,
|
||||
getSharedLinks,
|
||||
createSharedLink,
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ let releaseBalanceReservation: ReturnType<
|
|||
>['releaseBalanceReservation'];
|
||||
let findBalanceByUser: ReturnType<typeof createTransactionMethods>['findBalanceByUser'];
|
||||
let upsertBalanceFields: ReturnType<typeof createTransactionMethods>['upsertBalanceFields'];
|
||||
let initializeNullBalance: ReturnType<typeof createTransactionMethods>['initializeNullBalance'];
|
||||
let updateBalance: ReturnType<typeof createTransactionMethods>['updateBalance'];
|
||||
let getMultiplier: ReturnType<typeof createTxMethods>['getMultiplier'];
|
||||
let getCacheMultiplier: ReturnType<typeof createTxMethods>['getCacheMultiplier'];
|
||||
|
|
@ -64,6 +65,7 @@ beforeAll(async () => {
|
|||
findBalanceByUser = transactionMethods.findBalanceByUser;
|
||||
upsertBalanceFields = transactionMethods.upsertBalanceFields;
|
||||
updateBalance = transactionMethods.updateBalance;
|
||||
initializeNullBalance = transactionMethods.initializeNullBalance;
|
||||
|
||||
const spendMethods = createSpendTokensMethods(mongoose, {
|
||||
createTransaction: transactionMethods.createTransaction,
|
||||
|
|
@ -1863,3 +1865,41 @@ describe('Balance Reservations', () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeNullBalance admission CAS', () => {
|
||||
it.each([null, undefined])(
|
||||
'initializes legacy credit %s only once without upsert',
|
||||
async (credit) => {
|
||||
const user = new mongoose.Types.ObjectId().toString();
|
||||
await Balance.collection.insertOne({
|
||||
user: new mongoose.Types.ObjectId(user),
|
||||
...(credit === undefined ? {} : { tokenCredits: credit }),
|
||||
});
|
||||
const initialized = await initializeNullBalance(user, {
|
||||
tokenCredits: 100,
|
||||
sync: { autoRefillEnabled: true },
|
||||
});
|
||||
expect(initialized?.tokenCredits).toBe(100);
|
||||
expect(initialized?.autoRefillEnabled).toBe(true);
|
||||
await Balance.updateOne({ user }, { $set: { tokenCredits: 7 } });
|
||||
expect(await initializeNullBalance(user, { tokenCredits: 100 })).toBeNull();
|
||||
expect((await findBalanceByUser(user))?.tokenCredits).toBe(7);
|
||||
expect(await Balance.countDocuments({ user })).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it('chooses the oldest eligible row and never creates a missing balance', async () => {
|
||||
const user = new mongoose.Types.ObjectId().toString();
|
||||
expect(await initializeNullBalance(user, { tokenCredits: 100 })).toBeNull();
|
||||
const first = new mongoose.Types.ObjectId('000000000000000000000001');
|
||||
const second = new mongoose.Types.ObjectId('000000000000000000000002');
|
||||
await Balance.collection.insertMany([
|
||||
{ _id: second, user: new mongoose.Types.ObjectId(user), tokenCredits: null },
|
||||
{ _id: first, user: new mongoose.Types.ObjectId(user), tokenCredits: null },
|
||||
]);
|
||||
expect((await initializeNullBalance(user, { tokenCredits: 100 }))?._id.toString()).toBe(
|
||||
first.toString(),
|
||||
);
|
||||
expect((await Balance.findById(second).lean())?.tokenCredits).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -105,6 +105,10 @@ export function createTransactionMethods(
|
|||
user: string,
|
||||
options?: { includeReservedCredits?: boolean; applyReset?: boolean },
|
||||
) => Promise<IBalance | null>;
|
||||
initializeNullBalance: (
|
||||
user: string,
|
||||
input: { tokenCredits: number; sync?: IBalanceUpdate },
|
||||
) => Promise<IBalance | null>;
|
||||
upsertBalanceFields: (
|
||||
user: string,
|
||||
fields: IBalanceUpdate,
|
||||
|
|
@ -795,7 +799,21 @@ export function createTransactionMethods(
|
|||
}
|
||||
}
|
||||
|
||||
/** Null also matches legacy missing credit; a miss must never upsert or restore spent credit. */
|
||||
async function initializeNullBalance(
|
||||
user: string,
|
||||
{ tokenCredits, sync }: { tokenCredits: number; sync?: IBalanceUpdate },
|
||||
): Promise<IBalance | null> {
|
||||
const Balance = mongoose.models.Balance as Model<IBalance>;
|
||||
return Balance.findOneAndUpdate(
|
||||
{ user, tokenCredits: null },
|
||||
{ $set: { tokenCredits, ...(sync && Object.keys(sync).length > 0 ? sync : {}) } },
|
||||
{ new: true, sort: oldestFirst },
|
||||
).lean<IBalance>();
|
||||
}
|
||||
|
||||
return {
|
||||
initializeNullBalance,
|
||||
updateBalance,
|
||||
bulkInsertTransactions,
|
||||
findBalanceByUser,
|
||||
|
|
|
|||
|
|
@ -52,6 +52,9 @@ export function createUserMethods(
|
|||
mongoose: typeof import('mongoose'),
|
||||
deps: UserMethodDeps = {},
|
||||
): {
|
||||
findScheduleOwner: (
|
||||
userId: string,
|
||||
) => Promise<{ _id: string; tenantId?: string; role?: string; termsAccepted?: boolean } | null>;
|
||||
findUser: (
|
||||
searchCriteria: FilterQuery<IUser>,
|
||||
fieldsToSelect?: string | string[] | null,
|
||||
|
|
@ -1027,7 +1030,24 @@ export function createUserMethods(
|
|||
return updated;
|
||||
}
|
||||
|
||||
async function findScheduleOwner(
|
||||
userId: string,
|
||||
): Promise<{ _id: string; tenantId?: string; role?: string; termsAccepted?: boolean } | null> {
|
||||
const user = await mongoose.models.User.findById(userId)
|
||||
.select('_id tenantId role termsAccepted')
|
||||
.lean<IUser>();
|
||||
return user
|
||||
? {
|
||||
_id: user._id.toString(),
|
||||
tenantId: user.tenantId,
|
||||
role: user.role,
|
||||
termsAccepted: user.termsAccepted,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
return {
|
||||
findScheduleOwner,
|
||||
findUser,
|
||||
findUsers,
|
||||
findOwnerContactUsers,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue