mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-04-07 00:15:23 +02:00
* fix: Resolve custom role permissions not loading in frontend Users assigned to custom roles (non-USER/ADMIN) had all permission checks fail because AuthContext only fetched system role permissions. The roles map keyed by USER/ADMIN never contained the custom role name, so useHasAccess returned false for every feature gate. - Fetch the user's custom role in AuthContext and include it in the roles map so useHasAccess can resolve permissions correctly - Use encodeURIComponent instead of toLowerCase for role name URLs to preserve custom role casing through the API roundtrip - Only uppercase system role names on the backend GET route; pass custom role names through as-is for exact DB lookup - Allow users to fetch their own assigned role without READ_ROLES capability * refactor: Normalize all role names to uppercase Custom role names were stored in original casing, causing case-sensitivity bugs across the stack — URL lowercasing, route uppercasing, and case-sensitive DB lookups all conflicted for mixed-case custom roles. Enforce uppercase normalization at every boundary: - createRoleByName trims and uppercases the name before storage - createRoleHandler uppercases before passing to createRoleByName - All admin route handlers (get, update, delete, members, permissions) uppercase the :name URL param before DB lookups - addRoleMemberHandler uppercases before setting user.role - Startup migration (normalizeRoleNames) finds non-uppercase custom roles, renames them, and updates affected user.role values with collision detection Legacy GET /api/roles/:roleName retains always-uppercase behavior. Tests updated to expect uppercase role names throughout. * fix: Use case-preserved role names with strict equality Remove uppercase normalization — custom role names are stored and compared exactly as the user sets them, with only trimming applied. USER and ADMIN remain reserved case-insensitively via isSystemRoleName. - Remove toUpperCase from createRoleByName, createRoleHandler, and all admin route handlers (get, update, delete, members, permissions) - Remove toUpperCase from legacy GET and PUT routes in roles.js; the frontend now sends exact casing via encodeURIComponent - Remove normalizeRoleNames startup migration - Revert test expectations to original casing * fix: Format useMemo dependency array for Prettier * feat: Add custom role support to admin settings + review fixes - Add backend tests for isOwnRole authorization gate on GET /api/roles/:roleName - Add frontend tests for custom role detection and fetching in AuthContext - Fix transient null permission flash by only spreading custom role once loaded - Add isSystemRoleName helper to data-provider for case-insensitive system role detection - Use sentinel value in useGetRole to avoid ghost cache entry from empty string - Add useListRoles hook and listRoles data service for fetching all roles - Update AdminSettingsDialog and PeoplePickerAdminSettings to dynamically list custom roles in the role dropdown, with proper fallback defaults * fix: Address review findings for custom role permissions - Add assertions to AuthContext test verifying custom role in roles map - Fix empty array bypassing nullish coalescing fallback in role dropdowns - Add null/undefined guard to isSystemRoleName helper - Memoize role dropdown items to avoid unnecessary re-renders - Apply sentinel pattern to useGetRole in admin settings for consistency - Mark ListRolesResponse description as required to match schema * fix: Prevent prototype pollution in role authorization gate - Replace roleDefaults[roleName] with Object.hasOwn to prevent prototype chain bypass for names like constructor or __proto__ - Add dedicated rolesList query key to avoid cache collision when a custom role is named 'list' - Add regression test for prototype property name authorization * fix: Resolve Prettier formatting and unused variable lint errors * fix: Address review findings for custom role permissions - Add ADMIN self-read test documenting isOwnRole bypass behavior - Guard save button while custom role data loads to prevent data loss - Extract useRoleSelector hook eliminating ~55 lines of duplication - Unify defaultValues/useEffect permission resolution (fixes inconsistency) - Make ListRolesResponse.description and _id optional to match schema - Fix vacuous test assertions to verify sentinel calls exist - Only fetch userRole when user.role === USER (avoid unnecessary requests) - Remove redundant empty string guard in custom role detection * fix: Revert USER role fetch restriction to preserve admin settings Admins need the USER role loaded in AuthContext.roles so the admin settings dialog shows persisted USER permissions instead of defaults. * fix: Remove unused useEffect import from useRoleSelector * fix: Clean up useRoleSelector hook - Use existing isCustom variable instead of re-calling isSystemRoleName - Remove unused roles and availableRoleNames from return object * fix: Address review findings for custom role permissions - Use Set-based isSystemRoleName to auto-expand with future SystemRoles - Add isCustomRoleError handling: guard useEffect reset and disable Save - Remove resolvePermissions from hook return; use defaultValues in useEffect to eliminate redundant computation and stale-closure reset race - Rename customRoleName to userRoleName in AuthContext for clarity * fix: Request server-max roles for admin dropdown listRoles now passes limit=200 (the server's MAX_PAGE_LIMIT) so the admin role selector shows all roles instead of silently truncating at the default page size of 50. --------- Co-authored-by: Danny Avila <danny@librechat.ai>
209 lines
6.5 KiB
TypeScript
209 lines
6.5 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import * as Ariakit from '@ariakit/react';
|
|
import { ShieldEllipsis } from 'lucide-react';
|
|
import { useForm, Controller } from 'react-hook-form';
|
|
import { Permissions, SystemRoles, PermissionTypes } from 'librechat-data-provider';
|
|
import {
|
|
Button,
|
|
Switch,
|
|
OGDialog,
|
|
DropdownPopup,
|
|
OGDialogTitle,
|
|
OGDialogContent,
|
|
OGDialogTrigger,
|
|
useToastContext,
|
|
} from '@librechat/client';
|
|
import type { Control, UseFormSetValue, UseFormGetValues } from 'react-hook-form';
|
|
import { useUpdatePeoplePickerPermissionsMutation } from '~/data-provider';
|
|
import { useLocalize, useAuthContext, useRoleSelector } from '~/hooks';
|
|
|
|
type FormValues = {
|
|
[Permissions.VIEW_USERS]: boolean;
|
|
[Permissions.VIEW_GROUPS]: boolean;
|
|
[Permissions.VIEW_ROLES]: boolean;
|
|
};
|
|
|
|
type LabelControllerProps = {
|
|
label: string;
|
|
peoplePickerPerm: Permissions.VIEW_USERS | Permissions.VIEW_GROUPS | Permissions.VIEW_ROLES;
|
|
control: Control<FormValues, unknown, FormValues>;
|
|
setValue: UseFormSetValue<FormValues>;
|
|
getValues: UseFormGetValues<FormValues>;
|
|
};
|
|
|
|
const LabelController: React.FC<LabelControllerProps> = ({
|
|
control,
|
|
peoplePickerPerm,
|
|
label,
|
|
getValues,
|
|
setValue,
|
|
}) => (
|
|
<div className="mb-4 flex items-center justify-between gap-2">
|
|
<button
|
|
className="cursor-pointer select-none"
|
|
type="button"
|
|
onClick={() =>
|
|
setValue(peoplePickerPerm, !getValues(peoplePickerPerm), {
|
|
shouldDirty: true,
|
|
})
|
|
}
|
|
tabIndex={0}
|
|
>
|
|
{label}
|
|
</button>
|
|
<Controller
|
|
name={peoplePickerPerm}
|
|
control={control}
|
|
render={({ field }) => (
|
|
<Switch
|
|
{...field}
|
|
checked={field.value ?? false}
|
|
onCheckedChange={field.onChange}
|
|
value={(field.value ?? false).toString()}
|
|
aria-label={label}
|
|
/>
|
|
)}
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
const PeoplePickerAdminSettings = () => {
|
|
const localize = useLocalize();
|
|
const { showToast } = useToastContext();
|
|
const { user } = useAuthContext();
|
|
const { mutate, isLoading } = useUpdatePeoplePickerPermissionsMutation({
|
|
onSuccess: () => {
|
|
showToast({ status: 'success', message: localize('com_ui_saved') });
|
|
},
|
|
onError: () => {
|
|
showToast({ status: 'error', message: localize('com_ui_error_save_admin_settings') });
|
|
},
|
|
});
|
|
|
|
const [isRoleMenuOpen, setIsRoleMenuOpen] = useState(false);
|
|
const {
|
|
selectedRole,
|
|
isSelectedCustomRole,
|
|
isCustomRoleLoading,
|
|
isCustomRoleError,
|
|
defaultValues,
|
|
roleDropdownItems,
|
|
} = useRoleSelector(PermissionTypes.PEOPLE_PICKER);
|
|
|
|
const {
|
|
reset,
|
|
control,
|
|
setValue,
|
|
getValues,
|
|
handleSubmit,
|
|
formState: { isSubmitting },
|
|
} = useForm<FormValues>({
|
|
mode: 'onChange',
|
|
defaultValues: defaultValues as FormValues,
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (isSelectedCustomRole && (isCustomRoleLoading || isCustomRoleError)) {
|
|
return;
|
|
}
|
|
reset(defaultValues as FormValues);
|
|
}, [isSelectedCustomRole, isCustomRoleLoading, isCustomRoleError, defaultValues, reset]);
|
|
|
|
if (user?.role !== SystemRoles.ADMIN) {
|
|
return null;
|
|
}
|
|
|
|
const labelControllerData: {
|
|
peoplePickerPerm: Permissions.VIEW_USERS | Permissions.VIEW_GROUPS | Permissions.VIEW_ROLES;
|
|
label: string;
|
|
}[] = [
|
|
{
|
|
peoplePickerPerm: Permissions.VIEW_USERS,
|
|
label: localize('com_ui_people_picker_allow_view_users'),
|
|
},
|
|
{
|
|
peoplePickerPerm: Permissions.VIEW_GROUPS,
|
|
label: localize('com_ui_people_picker_allow_view_groups'),
|
|
},
|
|
{
|
|
peoplePickerPerm: Permissions.VIEW_ROLES,
|
|
label: localize('com_ui_people_picker_allow_view_roles'),
|
|
},
|
|
];
|
|
|
|
const onSubmit = (data: FormValues) => {
|
|
mutate({ roleName: selectedRole, updates: data });
|
|
};
|
|
|
|
return (
|
|
<OGDialog>
|
|
<OGDialogTrigger asChild>
|
|
<Button
|
|
variant={'outline'}
|
|
className="btn btn-neutral border-token-border-light relative gap-1 rounded-lg font-medium"
|
|
aria-label={localize('com_ui_admin_settings')}
|
|
>
|
|
<ShieldEllipsis className="cursor-pointer" aria-hidden="true" />
|
|
{localize('com_ui_admin_settings')}
|
|
</Button>
|
|
</OGDialogTrigger>
|
|
<OGDialogContent className="w-full border-border-light bg-surface-primary text-text-primary lg:w-1/4">
|
|
<OGDialogTitle>
|
|
{localize('com_ui_admin_settings_section', { section: localize('com_ui_people_picker') })}
|
|
</OGDialogTitle>
|
|
<div className="p-2">
|
|
{/* Role selection dropdown */}
|
|
<div className="flex items-center gap-2">
|
|
<span className="font-medium">{localize('com_ui_role_select')}:</span>
|
|
<DropdownPopup
|
|
unmountOnHide={true}
|
|
menuId="role-dropdown"
|
|
isOpen={isRoleMenuOpen}
|
|
setIsOpen={setIsRoleMenuOpen}
|
|
trigger={
|
|
<Ariakit.MenuButton className="inline-flex min-w-[6rem] items-center justify-center rounded-lg border border-border-light bg-transparent px-2 py-1 text-text-primary transition-all ease-in-out hover:bg-surface-tertiary">
|
|
{selectedRole}
|
|
</Ariakit.MenuButton>
|
|
}
|
|
items={roleDropdownItems}
|
|
itemClassName="items-center justify-center"
|
|
sameWidth={true}
|
|
/>
|
|
</div>
|
|
{/* Permissions form */}
|
|
<form onSubmit={handleSubmit(onSubmit)}>
|
|
<div className="py-5">
|
|
{labelControllerData.map(({ peoplePickerPerm, label }) => (
|
|
<div key={peoplePickerPerm}>
|
|
<LabelController
|
|
control={control}
|
|
peoplePickerPerm={peoplePickerPerm}
|
|
label={label}
|
|
getValues={getValues}
|
|
setValue={setValue}
|
|
/>
|
|
</div>
|
|
))}
|
|
</div>
|
|
<div className="flex justify-end">
|
|
<button
|
|
type="button"
|
|
onClick={handleSubmit(onSubmit)}
|
|
disabled={
|
|
isSubmitting ||
|
|
isLoading ||
|
|
(isSelectedCustomRole && (isCustomRoleLoading || isCustomRoleError))
|
|
}
|
|
className="btn rounded bg-green-500 font-bold text-white transition-all hover:bg-green-600"
|
|
>
|
|
{localize('com_ui_save')}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</OGDialogContent>
|
|
</OGDialog>
|
|
);
|
|
};
|
|
|
|
export default PeoplePickerAdminSettings;
|