mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-24 00:44:46 +00:00
* 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
124 lines
4.1 KiB
TypeScript
124 lines
4.1 KiB
TypeScript
import { logger } from '@librechat/data-schemas';
|
|
import type {
|
|
AuditActorInput,
|
|
RecordAuditEntryInput,
|
|
RecordAuditEntryOptions,
|
|
} from '@librechat/data-schemas';
|
|
import type { ServerRequest } from '~/types/http';
|
|
import { getSafeErrorMetadata } from '~/utils/errors';
|
|
import { buildAuditContext } from './context';
|
|
|
|
/** The `recordAuditEntry` data-schemas method, as handler factories receive it. */
|
|
export type RecordAuditEntry = (
|
|
input: RecordAuditEntryInput,
|
|
options?: RecordAuditEntryOptions,
|
|
) => Promise<unknown>;
|
|
|
|
/** An audit entry minus the parts derived from the request (actor, context). */
|
|
export type AdminAuditEvent = Omit<RecordAuditEntryInput, 'actor' | 'context'>;
|
|
|
|
export type AdminAuditEmitter = (req: ServerRequest, event: AdminAuditEvent) => Promise<void>;
|
|
|
|
/** Resolves the authenticated caller as an audit actor; null when unauthenticated. */
|
|
export function getAuditActor(req: ServerRequest): AuditActorInput | null {
|
|
const user = req.user;
|
|
const userId = user?._id?.toString() ?? user?.id;
|
|
if (!user || !userId) {
|
|
return null;
|
|
}
|
|
return { type: 'user', id: userId, name: user.name || user.username || user.email || userId };
|
|
}
|
|
|
|
/**
|
|
* Builds the audit writer shared by the admin handler factories. The caller is
|
|
* the actor and the request supplies forensic context; `tenantId` defaults to
|
|
* the caller's tenant unless the event sets the key (even to `undefined`, which
|
|
* routes the entry to the platform chain).
|
|
*
|
|
* Fail-open by default: a failed write is logged and the already-persisted
|
|
* mutation stands. With `failClosed`, the write error propagates so the
|
|
* handler's catch turns it into a 5xx.
|
|
*/
|
|
export function createAdminAuditEmitter(options: {
|
|
recordAuditEntry?: RecordAuditEntry;
|
|
failClosed?: boolean;
|
|
logPrefix: string;
|
|
}): AdminAuditEmitter {
|
|
const { recordAuditEntry, failClosed, logPrefix } = options;
|
|
return async function emitAdminAudit(req, event) {
|
|
if (!recordAuditEntry) {
|
|
return;
|
|
}
|
|
const actor = getAuditActor(req);
|
|
if (!actor) {
|
|
return;
|
|
}
|
|
const input: RecordAuditEntryInput = {
|
|
...event,
|
|
actor,
|
|
context: buildAuditContext(req),
|
|
tenantId: 'tenantId' in event ? event.tenantId : req.user?.tenantId,
|
|
};
|
|
if (failClosed) {
|
|
await recordAuditEntry(input, { failClosed: true });
|
|
return;
|
|
}
|
|
try {
|
|
await recordAuditEntry(input);
|
|
} catch (err) {
|
|
logger.error(
|
|
`${logPrefix} audit write failed for ${event.action}`,
|
|
getSafeErrorMetadata(err),
|
|
);
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Writes an entry for a change no request initiated (startup sync, IdP sync).
|
|
* Always fail-open: these paths run during startup or login and must not be
|
|
* blocked by the audit store.
|
|
*/
|
|
export async function recordSystemAuditEntry(
|
|
recordAuditEntry: RecordAuditEntry | undefined,
|
|
input: RecordAuditEntryInput,
|
|
logPrefix: string,
|
|
): Promise<void> {
|
|
if (!recordAuditEntry) {
|
|
return;
|
|
}
|
|
const logFailure = (err: unknown) =>
|
|
logger.error(`${logPrefix} audit write failed for ${input.action}`, getSafeErrorMetadata(err));
|
|
/** Dispatched without being awaited: login and startup must not wait on the audit store. */
|
|
try {
|
|
Promise.resolve(recordAuditEntry(input)).catch(logFailure);
|
|
} catch (err) {
|
|
logFailure(err);
|
|
}
|
|
}
|
|
|
|
type PermissionMap = Record<string, Record<string, boolean | undefined> | undefined>;
|
|
|
|
/**
|
|
* Lists the permission flags that differ between two role permission maps as
|
|
* sorted `TYPE.FIELD=value` strings, so an audit entry records what changed
|
|
* without storing the whole role document.
|
|
*/
|
|
export function diffRolePermissions(
|
|
before: PermissionMap | undefined,
|
|
after: PermissionMap | undefined,
|
|
): string[] {
|
|
const changes: string[] = [];
|
|
const types = new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]);
|
|
for (const type of types) {
|
|
const prev = before?.[type] ?? {};
|
|
const next = after?.[type] ?? {};
|
|
const fields = new Set([...Object.keys(prev), ...Object.keys(next)]);
|
|
for (const field of fields) {
|
|
if (prev[field] !== next[field]) {
|
|
changes.push(`${type}.${field}=${String(next[field])}`);
|
|
}
|
|
}
|
|
}
|
|
return changes.sort();
|
|
}
|