LibreChat/api/server/routes/__tests__/roles.spec.js
Marco Beretta ccae5b988d
📜 feat: Audit Admin Role, Group, Config and IdP Role Mutations (#17052)
* feat: Extend the Audit Action Vocabulary to Admin, Sync and Credential Mutations

* feat: Audit Admin Role, Group and Config Mutations

Role deletion now removes the role's grants, ACL entries and config
overrides before the role itself and returns ROLE_CLEANUP_FAILED instead
of success when any of them fails, so a recreated role cannot inherit
leftover privileges.

* feat: Audit IdP and Startup Role Changes

* fix: Keep the Startup Role Sync Running When Its Audit Verification Read Fails

* test: Cover Admin Role Audit Trail End to End

* fix: Audit a Remote Agent Role Sync Only After It Persists

* fix: Restore Role Dependents When Role Deletion Fails Midway

* fix: Restore Role Dependents Only When the Role Still Exists

* style: Sort Role Admin Imports

* fix: Keep the ACL Snapshot When Role Cleanup Fails Ambiguously

* test: Read Role Audit Entries From the Audit Log Route

* fix: Audit Only Real Membership Changes and Restore Deleted Role Config in Full

* fix: Restore Deleted Role Grants in Full and Sanitize Audit Write Logging

* fix: Audit and Report a Role Deletion Confirmed After a Lost Response

* fix: Never Restore Dependents Onto a Recreated Role

* fix: Snapshot Role Dependents Before Deleting and Detect Membership Changes Atomically

* fix: Restore From the Data a Cascade Step Actually Removed

* fix: Restore Only Config Overrides When a Role Delete Fails

* fix: Log Only Safe Metadata When the Startup Audit Read Fails

* fix: Audit Grants Removed by a Failed Role Delete

* fix: Audit Removed Grants on Unverifiable Role Delete Exits

* fix: Honor Fail-Closed Auditing in the Admin Config, Group and Role Routes

* fix: Bind Role Deletion to the Captured Id and Audit Only Atomic Role and Config Changes

* fix: Skip the Config Restore When the Targeted Role Is Gone

* fix: Audit Initial Group Members and Skip No-Op Role Description Updates

* fix: Record Role Deletion as Pending Before Cleanup and Append Its Outcome

* fix: Audit Reassigned Role Members and Return the Persisted Config After a Tracked Toggle

* fix: Keep a Committed Role Deletion Successful When Cascade Audit Writes Fail

* fix: Decide Group Update Audits From the Atomic Write and Sanitize Permission Update Logs

* fix: Audit Grants From a Snapshot, Fail on Member Lookup Errors and Chunk Member Audit Entries

* fix: Audit Group Deletion Members and Previous Role Removal, Abort on Grant Snapshot Failure

* fix: Invalidate Config Caches After Partial Secret Writes

* fix: Retry Failed Cascade Restores, Report Changed Group Fields and Audit Every Reassigned Member

* fix: Log Safe Metadata When Cache Invalidation Fails After a Partial Write

* fix: Keep Error Messages Out of the Audit Write Failure Log

* style: Sort Audit Log Spec Imports

* fix: Sanitize Admin Handler Error Logs and Dispatch System Audit Writes Without Waiting
2026-10-14 23:57:07 +02:00

230 lines
7.8 KiB
JavaScript

const express = require('express');
const request = require('supertest');
const { SystemRoles, roleDefaults } = require('librechat-data-provider');
const mockGetRoleByName = jest.fn();
const mockUpdateRoleByName = jest.fn();
const mockRecordAuditEntry = jest.fn();
const mockHasCapability = jest.fn();
jest.mock('~/server/middleware', () => ({
requireJwtAuth: (_req, _res, next) => next(),
}));
jest.mock('~/server/middleware/roles/capabilities', () => ({
hasCapability: (...args) => mockHasCapability(...args),
requireCapability: () => (_req, _res, next) => next(),
}));
jest.mock('~/models', () => ({
getRoleByName: (...args) => mockGetRoleByName(...args),
updateRoleByName: (...args) => mockUpdateRoleByName(...args),
recordAuditEntry: (...args) => mockRecordAuditEntry(...args),
}));
const rolesRouter = require('../roles');
function createApp(user) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.user = user;
next();
});
app.use('/api/roles', rolesRouter);
return app;
}
const staffRole = {
name: 'STAFF',
permissions: {
PROMPTS: { USE: true, CREATE: false },
},
};
const userRole = roleDefaults[SystemRoles.USER];
const adminRole = roleDefaults[SystemRoles.ADMIN];
beforeEach(() => {
jest.clearAllMocks();
mockHasCapability.mockResolvedValue(false);
mockGetRoleByName.mockResolvedValue(null);
});
describe('GET /api/roles/:roleName — isOwnRole authorization', () => {
it('allows a custom role user to fetch their own role', async () => {
mockGetRoleByName.mockResolvedValue(staffRole);
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get('/api/roles/STAFF');
expect(res.status).toBe(200);
expect(res.body.name).toBe('STAFF');
expect(mockGetRoleByName).toHaveBeenCalledWith('STAFF', '-_id -__v');
expect(mockHasCapability).not.toHaveBeenCalled();
});
it('returns 403 when a custom role user requests a different custom role', async () => {
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get('/api/roles/MANAGER');
expect(res.status).toBe(403);
expect(mockGetRoleByName).not.toHaveBeenCalled();
});
it('returns 403 when a custom role user requests ADMIN', async () => {
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get('/api/roles/ADMIN');
expect(res.status).toBe(403);
expect(mockGetRoleByName).not.toHaveBeenCalled();
});
it('allows USER to fetch the USER role (roleDefaults key)', async () => {
mockGetRoleByName.mockResolvedValue(userRole);
const app = createApp({ id: 'u1', role: SystemRoles.USER });
const res = await request(app).get(`/api/roles/${SystemRoles.USER}`);
expect(res.status).toBe(200);
expect(mockHasCapability).not.toHaveBeenCalled();
});
it('allows a custom role user to fetch a non-admin default role without a capability probe', async () => {
mockGetRoleByName.mockResolvedValue(userRole);
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get(`/api/roles/${SystemRoles.USER}`);
expect(res.status).toBe(200);
expect(mockHasCapability).not.toHaveBeenCalled();
});
it('returns 403 when USER requests the ADMIN role', async () => {
const app = createApp({ id: 'u1', role: SystemRoles.USER });
const res = await request(app).get(`/api/roles/${SystemRoles.ADMIN}`);
expect(res.status).toBe(403);
});
it('allows ADMIN user to fetch their own ADMIN role via isOwnRole', async () => {
mockHasCapability.mockResolvedValue(false);
mockGetRoleByName.mockResolvedValue(adminRole);
const app = createApp({ id: 'u1', role: SystemRoles.ADMIN });
const res = await request(app).get(`/api/roles/${SystemRoles.ADMIN}`);
expect(res.status).toBe(200);
expect(mockHasCapability).not.toHaveBeenCalled();
});
it('allows any user with READ_ROLES capability to fetch any role', async () => {
mockHasCapability.mockResolvedValue(true);
mockGetRoleByName.mockResolvedValue(staffRole);
const app = createApp({ id: 'u1', role: SystemRoles.USER });
const res = await request(app).get('/api/roles/STAFF');
expect(res.status).toBe(200);
expect(res.body.name).toBe('STAFF');
});
it('probes READ_ROLES with a coerced CapabilityUser for non-own-role lookups', async () => {
mockHasCapability.mockResolvedValue(true);
mockGetRoleByName.mockResolvedValue(staffRole);
const app = createApp({ id: 'u1', role: SystemRoles.USER });
const res = await request(app).get('/api/roles/STAFF');
expect(res.status).toBe(200);
expect(mockHasCapability).toHaveBeenCalledTimes(1);
expect(mockHasCapability).toHaveBeenCalledWith(
{ id: 'u1', role: SystemRoles.USER, tenantId: undefined, idOnTheSource: null },
expect.any(String),
);
});
it('returns 404 when the requested role does not exist', async () => {
mockGetRoleByName.mockResolvedValue(null);
const app = createApp({ id: 'u1', role: 'GHOST' });
const res = await request(app).get('/api/roles/GHOST');
expect(res.status).toBe(404);
});
it('returns 500 when getRoleByName throws', async () => {
mockGetRoleByName.mockRejectedValue(new Error('db error'));
const app = createApp({ id: 'u1', role: SystemRoles.USER });
const res = await request(app).get(`/api/roles/${SystemRoles.USER}`);
expect(res.status).toBe(500);
});
it('returns 403 for prototype property names like constructor (no prototype pollution)', async () => {
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get('/api/roles/constructor');
expect(res.status).toBe(403);
expect(mockGetRoleByName).not.toHaveBeenCalled();
});
it('serves own role without probing even when hasCapability would fail', async () => {
mockHasCapability.mockRejectedValue(new Error('capability check failed'));
const app = createApp({ id: 'u1', role: 'STAFF' });
mockGetRoleByName.mockResolvedValue(staffRole);
const res = await request(app).get('/api/roles/STAFF');
expect(res.status).toBe(200);
expect(mockHasCapability).not.toHaveBeenCalled();
});
it('treats hasCapability failure as no capability for other roles (403, not 500)', async () => {
mockHasCapability.mockRejectedValue(new Error('capability check failed'));
const app = createApp({ id: 'u1', role: 'STAFF' });
const res = await request(app).get('/api/roles/MANAGER');
expect(res.status).toBe(403);
expect(mockGetRoleByName).not.toHaveBeenCalled();
});
});
describe('PUT /api/roles/:roleName/prompts', () => {
it('merges the update and records the permission change', async () => {
mockGetRoleByName.mockResolvedValue(staffRole);
mockUpdateRoleByName.mockImplementation(async (name, updates) => ({ name, ...updates }));
mockRecordAuditEntry.mockResolvedValue(null);
const app = createApp({ id: 'u1', _id: 'u1', role: SystemRoles.ADMIN, name: 'Admin' });
const res = await request(app).put('/api/roles/STAFF/prompts').send({ CREATE: true });
expect(res.status).toBe(200);
expect(mockUpdateRoleByName).toHaveBeenCalledWith('STAFF', {
permissions: { PROMPTS: { USE: true, CREATE: true } },
});
expect(mockRecordAuditEntry).toHaveBeenCalledWith(
expect.objectContaining({
action: 'role.permissions_updated',
target: { type: 'role', id: 'STAFF', name: 'STAFF' },
metadata: { changes: 'PROMPTS.CREATE=true', changeCount: 1 },
}),
);
});
it('returns 400 for an invalid body without writing', async () => {
const app = createApp({ id: 'u1', role: SystemRoles.ADMIN });
const res = await request(app).put('/api/roles/STAFF/prompts').send({ CREATE: 'yes' });
expect(res.status).toBe(400);
expect(res.body.message).toBe('Invalid prompt permissions.');
expect(mockUpdateRoleByName).not.toHaveBeenCalled();
});
});