LibreChat/api/server/middleware/optionalShareFileAuth.spec.js
Marco Beretta 02a70e9c58
⏳ feat: Add Ephemeral Retention Mode for Forced Temporary Chats (#13811)
* feat: add ephemeral retention mode for forced temporary chats

Adds RetentionMode.EPHEMERAL, which forces every newly saved chat
temporary: hidden from history and search, given the temporary-chat
expiration, and with the toggle locked on.

Forces isTemporary and applies the temporary expiration in the normal
conversation and message save methods, routes Assistants/Threads
messages through the normal message save, applies the all-data
retention policy to file uploads and shared links, and stamps imports,
forks, and duplicates. Locks the frontend toggle and keyboard shortcut
behind an administrator-enforced badge.

The default temporary mode and the existing all mode are unchanged.

* fix: enforce ephemeral retention when resuming paused chats

* fix: preserve forced retention across pauses and assistant turns

* test: Use Real Module IDs for Installed Package Mocks

* test: Wait for Resumed Retention Persistence

* test: Control Mongo Index Setup in OpenID Fixture

* test: Close Mobile Drawer Before Retention Resume Scenario

* fix: Store Responses API Messages Under the Retention Write Context

Input and output messages were saved with the raw request, so under
ephemeral retention they missed the forced-temporary classification the
conversation received. Route both through getConversationWriteContext
and announce the stored reply as saved.

* fix: Align Resumed Responses With the Parent Retention Deadline

A resumed response was saved with a fresh forced-temporary window while
the re-stamp kept the conversation's earlier deadline, so a chat that
paused again could leave its response stored after the conversation
expired. Stamp the saved response with the parent's deadline.

* fix: Clear Released Bookmark Tags When Forcing a Chat Temporary

stampForcedRetention released a converted chat's bookmark counts but
kept its tags, so deleting that chat before TTL removal decremented the
same tags again and reduced counts owned by other visible chats. Clear
the tags in the conditional conversion update that releases them.

* fix: Store No Bookmark Tags on Forced-Temporary Imports

An ephemeral import, fork or duplicate skipped its tag count increment
but kept the source tags, so deleting the copy before TTL removal
decremented counts owned by other visible chats. Store the same tags the
import counts, which is none for a forced-temporary copy.

* test: Provide the Forced-Temporary Retention Helper to the Header Stacking Mock

* test: Reuse One Admin Login per Worker in Ephemeral Retention Scenarios

* fix: Keep Legacy Temporary Chats Temporary When Forking Under All-Data Retention

* fix: Convert a Resumed Chat Under Ephemeral Retention Before It Can Re-Pause Empty

* fix: Treat a Reloaded Pre-Policy Run as Temporary Once Retention Is Forced

* fix: Stamp Messages with the Deadline a Concurrent Retention Stamp Stored

* fix: Wait for the Startup Config Before Rebuilding a Resumed Submission

* test: Wait for the Resumed Response Row in the Ephemeral Resume Scenario

* test: Provide the Real Command Executor Stamp to the Callbacks Mock
2026-09-30 18:57:28 +02:00

137 lines
5.2 KiB
JavaScript

const mockVerify = jest.fn();
const mockGetUserById = jest.fn();
const mockFindSession = jest.fn();
const mockRunAsSystem = jest.fn((fn) => fn());
jest.mock('jsonwebtoken', () => ({ verify: (...args) => mockVerify(...args) }));
/** Installed packages need real module IDs when Jest reuses a resolver across suites. */
jest.mock('@librechat/api', () => ({ isEnabled: (v) => v === 'true' || v === true }), {
virtual: false,
});
jest.mock(
'@librechat/data-schemas',
() => ({
logger: { warn: jest.fn(), error: jest.fn() },
runAsSystem: (...args) => mockRunAsSystem(...args),
}),
{ virtual: false },
);
jest.mock('librechat-data-provider', () => ({ SystemRoles: { USER: 'USER' } }), {
virtual: false,
});
jest.mock('~/models', () => ({
getUserById: (...args) => mockGetUserById(...args),
findSession: (...args) => mockFindSession(...args),
}));
const optionalShareFileAuth = require('./optionalShareFileAuth');
const run = async (req) => {
const next = jest.fn();
await optionalShareFileAuth(req, {}, next);
return next;
};
describe('optionalShareFileAuth', () => {
beforeEach(() => {
jest.clearAllMocks();
process.env.JWT_REFRESH_SECRET = 'test-secret';
});
it('short-circuits when a bearer user is already set (no cookie work)', async () => {
const req = { user: { id: 'u1' }, headers: { cookie: 'refreshToken=x' } };
const next = await run(req);
expect(next).toHaveBeenCalledTimes(1);
expect(mockVerify).not.toHaveBeenCalled();
expect(mockGetUserById).not.toHaveBeenCalled();
expect(mockFindSession).not.toHaveBeenCalled();
});
it('resolves the viewer from a valid refreshToken cookie with a live session', async () => {
mockVerify.mockReturnValue({ id: 'viewer-1' });
mockFindSession.mockResolvedValue({ _id: 'session-1' });
mockGetUserById.mockResolvedValue({ _id: 'viewer-1', role: 'USER' });
const req = { headers: { cookie: 'refreshToken=good.jwt' } };
const next = await run(req);
expect(next).toHaveBeenCalledTimes(1);
expect(mockVerify).toHaveBeenCalledWith('good.jwt', 'test-secret');
expect(mockFindSession).toHaveBeenCalledWith({ userId: 'viewer-1', refreshToken: 'good.jwt' });
expect(mockRunAsSystem).toHaveBeenCalledTimes(2);
expect(req.user).toMatchObject({ id: 'viewer-1', role: 'USER' });
});
it('defaults the role to USER when the record has none', async () => {
mockVerify.mockReturnValue({ id: 'viewer-2' });
mockFindSession.mockResolvedValue({ _id: 'session-2' });
mockGetUserById.mockResolvedValue({ _id: 'viewer-2' });
const req = { headers: { cookie: 'refreshToken=good.jwt' } };
await run(req);
expect(req.user.role).toBe('USER');
});
it('leaves req.user unset when there is no cookie', async () => {
const req = { headers: {} };
const next = await run(req);
expect(next).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
expect(mockGetUserById).not.toHaveBeenCalled();
});
it('leaves req.user unset when the refresh token has no live session', async () => {
mockVerify.mockReturnValue({ id: 'viewer-3' });
mockFindSession.mockResolvedValue(null);
const req = { headers: { cookie: 'refreshToken=revoked.jwt' } };
const next = await run(req);
expect(next).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
expect(mockFindSession).toHaveBeenCalledWith({
userId: 'viewer-3',
refreshToken: 'revoked.jwt',
});
expect(mockRunAsSystem).toHaveBeenCalledTimes(1);
expect(mockGetUserById).not.toHaveBeenCalled();
});
it('leaves req.user unset when the token is invalid', async () => {
mockVerify.mockImplementation(() => {
throw new Error('bad token');
});
const req = { headers: { cookie: 'refreshToken=bad' } };
const next = await run(req);
expect(next).toHaveBeenCalledTimes(1);
expect(req.user).toBeUndefined();
expect(mockGetUserById).not.toHaveBeenCalled();
});
it('uses the signed openid_user_id cookie only for active OpenID-reuse sessions', async () => {
process.env.OPENID_REUSE_TOKENS = 'true';
mockVerify.mockReturnValue({ id: 'oidc-1' });
mockGetUserById.mockResolvedValue({ _id: 'oidc-1', role: 'USER' });
const req = {
headers: {
cookie: 'token_provider=openid; refreshToken=stored-refresh; openid_user_id=signed.jwt',
},
session: { openidTokens: { refreshToken: 'stored-refresh' } },
};
await run(req);
expect(mockVerify).toHaveBeenCalledWith('signed.jwt', 'test-secret');
expect(mockFindSession).not.toHaveBeenCalled();
expect(req.user).toMatchObject({ id: 'oidc-1' });
delete process.env.OPENID_REUSE_TOKENS;
});
it('leaves req.user unset for OpenID-reuse cookies without an active matching session', async () => {
process.env.OPENID_REUSE_TOKENS = 'true';
mockVerify.mockReturnValue({ id: 'oidc-2' });
const req = {
headers: {
cookie: 'token_provider=openid; refreshToken=stale-refresh; openid_user_id=signed.jwt',
},
session: { openidTokens: { refreshToken: 'current-refresh' } },
};
await run(req);
expect(req.user).toBeUndefined();
expect(mockGetUserById).not.toHaveBeenCalled();
delete process.env.OPENID_REUSE_TOKENS;
});
});