From 4d7078b2961003c8b12bc944fc0213dd32f9e07a Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Thu, 15 Oct 2026 14:03:49 +1100 Subject: [PATCH 1/7] feat(authz): add the AuthZ catalog feature Fetch the roles, permissions and categories catalog of the scope types the user can view, slice it by scope type, order its roles by permission count, and render its icons by name with CatalogIcon. Nothing consumes it yet. Co-Authored-By: Claude Opus 5.5 --- src/authz-module/catalog/CatalogIcon.test.tsx | 47 ++++++ src/authz-module/catalog/CatalogIcon.tsx | 49 ++++++ src/authz-module/catalog/constants.ts | 2 + src/authz-module/catalog/data/api.ts | 52 ++++++ src/authz-module/catalog/data/hooks.test.tsx | 149 ++++++++++++++++++ src/authz-module/catalog/data/hooks.ts | 77 +++++++++ src/authz-module/catalog/index.ts | 5 + src/authz-module/catalog/testUtils.ts | 110 +++++++++++++ src/authz-module/catalog/types.ts | 46 ++++++ src/authz-module/catalog/utils.test.ts | 88 +++++++++++ src/authz-module/catalog/utils.ts | 42 +++++ src/authz-module/constants.ts | 12 ++ 12 files changed, 679 insertions(+) create mode 100644 src/authz-module/catalog/CatalogIcon.test.tsx create mode 100644 src/authz-module/catalog/CatalogIcon.tsx create mode 100644 src/authz-module/catalog/constants.ts create mode 100644 src/authz-module/catalog/data/api.ts create mode 100644 src/authz-module/catalog/data/hooks.test.tsx create mode 100644 src/authz-module/catalog/data/hooks.ts create mode 100644 src/authz-module/catalog/index.ts create mode 100644 src/authz-module/catalog/testUtils.ts create mode 100644 src/authz-module/catalog/types.ts create mode 100644 src/authz-module/catalog/utils.test.ts create mode 100644 src/authz-module/catalog/utils.ts diff --git a/src/authz-module/catalog/CatalogIcon.test.tsx b/src/authz-module/catalog/CatalogIcon.test.tsx new file mode 100644 index 00000000..08362099 --- /dev/null +++ b/src/authz-module/catalog/CatalogIcon.test.tsx @@ -0,0 +1,47 @@ +import { render, waitFor } from '@testing-library/react'; +import { Icon } from '@openedx/paragon'; +import { RemoveRedEye } from '@openedx/paragon/icons'; +import CatalogIcon from './CatalogIcon'; + +describe('CatalogIcon', () => { + it('shows the Paragon icon the catalog names', async () => { + const { container: expected } = render(); + + const { container } = render(); + + await waitFor(() => expect(container.innerHTML).toBe(expected.innerHTML)); + }); + + it('shows the same icon wherever the catalog names it', async () => { + const { container: expected } = render(); + + const { container } = render( + <> + + + , + ); + + await waitFor(() => expect(container.innerHTML).toBe(expected.innerHTML.repeat(2))); + }); + + it('keeps an empty icon in place when the name is not a Paragon icon', async () => { + const { container } = render(); + + await waitFor(() => expect(container.querySelector('.pgn__icon')).toBeInTheDocument()); + expect(container.querySelector('svg')).not.toBeInTheDocument(); + }); + + it('keeps an empty icon in place when the name is not a valid icon name', async () => { + const { container } = render(); + + await waitFor(() => expect(container.querySelector('.pgn__icon')).toBeInTheDocument()); + expect(container.querySelector('svg')).not.toBeInTheDocument(); + }); + + it('renders nothing when the catalog sends no icon', () => { + const { container } = render(); + + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/src/authz-module/catalog/CatalogIcon.tsx b/src/authz-module/catalog/CatalogIcon.tsx new file mode 100644 index 00000000..6f760ba5 --- /dev/null +++ b/src/authz-module/catalog/CatalogIcon.tsx @@ -0,0 +1,49 @@ +import { + ComponentProps, ComponentType, lazy, LazyExoticComponent, Suspense, +} from 'react'; +import { Icon } from '@openedx/paragon'; + +type IconProps = Omit, 'src'>; + +interface CatalogIconProps extends IconProps { + // Paragon icon name, as the catalog API sends it (e.g. `RemoveRedEye`). + name: string | null; +} + +const ICON_NAME_PATTERN = /^[A-Za-z0-9]+$/; + +const NoIcon = () => null; + +// One lazy component per icon name, so each icon is downloaded once and shared by every render. +const lazyIcons = new Map>(); + +const getLazyIcon = (name: string) => { + if (!lazyIcons.has(name)) { + lazyIcons.set(name, lazy(() => ( + ICON_NAME_PATTERN.test(name) + // `index.js` re-exports every icon, so it stays out of the lazy chunks. + ? import(/* webpackExclude: /index\.js$/ */ `@openedx/paragon/icons/es5/${name}.js`) + .catch(() => ({ default: NoIcon })) + : Promise.resolve({ default: NoIcon }) + ))); + } + return lazyIcons.get(name)!; +}; + +/** + * Renders the Paragon icon the catalog names, downloading only that icon. + * + * While the icon loads, and when the name is unknown, it renders an empty icon of the same size, so + * the layout doesn't shift. When the catalog sends no icon, it renders nothing. + */ +const CatalogIcon = ({ name, ...iconProps }: CatalogIconProps) => { + if (!name) return null; + + return ( + }> + + + ); +}; + +export default CatalogIcon; diff --git a/src/authz-module/catalog/constants.ts b/src/authz-module/catalog/constants.ts new file mode 100644 index 00000000..718175dc --- /dev/null +++ b/src/authz-module/catalog/constants.ts @@ -0,0 +1,2 @@ +// Maximum page size accepted by the catalog API. +export const CATALOG_PAGE_SIZE = 100; diff --git a/src/authz-module/catalog/data/api.ts b/src/authz-module/catalog/data/api.ts new file mode 100644 index 00000000..f787e401 --- /dev/null +++ b/src/authz-module/catalog/data/api.ts @@ -0,0 +1,52 @@ +import { camelCaseObject, getAuthenticatedHttpClient } from '@openedx/frontend-base'; +import { getApiUrl } from '@src/data/utils'; +import { CATALOG_PAGE_SIZE } from '../constants'; +import type { + AuthzCatalog, Category, Permission, Role, +} from '../types'; + +export interface GetAuthzCatalogResponse { + count: number; + next: string | null; + previous: string | null; + scopeTypes: string[]; + categories: Category[]; + permissions: Permission[]; + results: Role[]; +} + +const getAuthzCatalogPage = async (scopeTypes: string[], page: number): Promise => { + const url = new URL(getApiUrl('/api/authz/v1/roles/')); + url.searchParams.set('scope_types', scopeTypes.join(',')); + url.searchParams.set('page', page.toString()); + url.searchParams.set('page_size', CATALOG_PAGE_SIZE.toString()); + const { data } = await getAuthenticatedHttpClient().get(url); + return camelCaseObject(data); +}; + +/** + * Fetches the complete roles, permissions and categories catalog of the given scope types. + * + * Only the roles are paginated; categories and permissions are complete on every page, so they + * are taken from the first one. The first page is requested at the maximum page size and, if + * there are more, the remaining pages are fetched in parallel and their roles appended in order. + */ +export const getAuthzCatalog = async (scopeTypes: string[]): Promise => { + const firstPage = await getAuthzCatalogPage(scopeTypes, 1); + const pages = [firstPage]; + + if (firstPage.next) { + const totalPages = Math.ceil(firstPage.count / CATALOG_PAGE_SIZE); + const remainingPages = await Promise.all( + Array.from({ length: totalPages - 1 }, (_, index) => getAuthzCatalogPage(scopeTypes, index + 2)), + ); + pages.push(...remainingPages); + } + + return { + scopeTypes: firstPage.scopeTypes, + categories: firstPage.categories, + permissions: firstPage.permissions, + roles: pages.flatMap((page) => page.results), + }; +}; diff --git a/src/authz-module/catalog/data/hooks.test.tsx b/src/authz-module/catalog/data/hooks.test.tsx new file mode 100644 index 00000000..d8211f2f --- /dev/null +++ b/src/authz-module/catalog/data/hooks.test.tsx @@ -0,0 +1,149 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import { createQueryClientWrapper, mockHttpClient } from '@src/testUtils'; +import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; +import { CATALOG_PAGE_SIZE } from '../constants'; +import { useAuthzCatalog } from './hooks'; + +jest.mock('@openedx/frontend-base', () => ({ + ...jest.requireActual('@openedx/frontend-base'), + getAuthenticatedHttpClient: jest.fn(), +})); + +interface MockApiOptions { + course?: boolean; + library?: boolean; + isPermissionsPending?: boolean; +} + +const buildPermission = (id: string, scopeType: string) => ({ + id, display_name: id, description: '', icon: null, category_id: null, scope_types: [scopeType], +}); + +const buildRole = (role: string, permissions: string[], scopeType: string) => ({ + role, display_name: role, description: '', icon: null, definition_kind: 'static', permissions, scope_types: [scopeType], +}); + +// Answers validate/me with the given view-team permissions, and the catalog endpoint with a +// course role and a library role, for the scope types that were requested. +const mockApi = ({ course = false, library = false, isPermissionsPending = false }: MockApiOptions) => { + const post = jest.fn(() => (isPermissionsPending ? new Promise(() => {}) : Promise.resolve({ + data: [ + { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.COURSE], allowed: course }, + { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.LIBRARY], allowed: library }, + ], + }))); + const get = jest.fn((url: URL) => Promise.resolve({ + data: { + count: 0, + next: null, + previous: null, + scope_types: url.searchParams.get('scope_types')?.split(','), + categories: [], + permissions: [ + buildPermission('courses.view_course', SCOPE_TYPES.COURSE), + buildPermission('content_libraries.view_library', SCOPE_TYPES.LIBRARY), + ], + results: [ + buildRole('course_admin', ['courses.view_course'], SCOPE_TYPES.COURSE), + buildRole('library_admin', ['content_libraries.view_library'], SCOPE_TYPES.LIBRARY), + ], + }, + })); + mockHttpClient().mockReturnValue({ get, post }); + return { get, post }; +}; + +const renderUseAuthzCatalog = () => renderHook(() => useAuthzCatalog(), { wrapper: createQueryClientWrapper() }); + +describe('useAuthzCatalog', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('fetches the catalog of every scope type the user can view', async () => { + mockApi({ course: true, library: true }); + + const { result } = renderUseAuthzCatalog(); + + await waitFor(() => expect(result.current.scopeTypes).toEqual([SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY])); + }); + + it('fetches only the library catalog when the user can only view library teams', async () => { + mockApi({ library: true }); + + const { result } = renderUseAuthzCatalog(); + + await waitFor(() => expect(result.current.scopeTypes).toEqual([SCOPE_TYPES.LIBRARY])); + }); + + it('gives the catalog of each scope type the user can view', async () => { + mockApi({ course: true, library: true }); + + const { result } = renderUseAuthzCatalog(); + + await waitFor(() => expect( + result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)?.roles.map(({ role }) => role), + ).toEqual(['library_admin'])); + expect(result.current.getScopeCatalog(SCOPE_TYPES.COURSE)?.roles.map(({ role }) => role)).toEqual(['course_admin']); + }); + + it('keeps the same scope type catalog between renders', async () => { + mockApi({ library: true }); + + const { result, rerender } = renderUseAuthzCatalog(); + await waitFor(() => expect(result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)).toBeDefined()); + const libraryCatalog = result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY); + + rerender(); + + expect(result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)).toBe(libraryCatalog); + }); + + it('is loading while the view permissions are being resolved', () => { + const { get } = mockApi({ isPermissionsPending: true }); + + const { result } = renderUseAuthzCatalog(); + + expect(result.current.isLoading).toBe(true); + expect(get).not.toHaveBeenCalled(); + }); + + it('does not fetch a catalog when the user cannot view any team', async () => { + const { get } = mockApi({}); + + const { result } = renderUseAuthzCatalog(); + + await waitFor(() => expect(result.current.isLoading).toBe(false)); + expect(result.current.scopeTypes).toEqual([]); + expect(result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)).toBeUndefined(); + expect(get).not.toHaveBeenCalled(); + }); + + it('lists the roles of every page, in order, when they do not fit in one page', async () => { + const { post } = mockApi({ library: true }); + // Three pages of roles, one role in each. + const get = jest.fn((url: URL) => { + const page = Number(url.searchParams.get('page')); + return Promise.resolve({ + data: { + count: CATALOG_PAGE_SIZE * 2 + 1, + next: page < 3 ? 'next-page' : null, + previous: null, + scope_types: [SCOPE_TYPES.LIBRARY], + categories: [], + permissions: [], + results: [{ + role: `role_page_${page}`, display_name: '', description: '', icon: null, definition_kind: 'static', permissions: [], scope_types: [SCOPE_TYPES.LIBRARY], + }], + }, + }); + }); + mockHttpClient().mockReturnValue({ get, post }); + + const { result } = renderUseAuthzCatalog(); + + await waitFor(() => expect( + result.current.data?.roles.map(({ role }) => role), + ).toEqual(['role_page_1', 'role_page_2', 'role_page_3'])); + }); +}); diff --git a/src/authz-module/catalog/data/hooks.ts b/src/authz-module/catalog/data/hooks.ts new file mode 100644 index 00000000..a319f913 --- /dev/null +++ b/src/authz-module/catalog/data/hooks.ts @@ -0,0 +1,77 @@ +import { useCallback, useMemo } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { appId } from '@src/constants'; +import { useValidateUserPermissionsNonSuspense } from '@src/data/hooks'; +import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; +import { getAuthzCatalog } from './api'; +import type { AuthzCatalog, ScopeCatalog } from '../types'; +import { getScopeCatalog } from '../utils'; + +const catalogQueryKeys = { + all: [appId, 'authz', 'catalog'] as const, + byScopeTypes: (scopeTypes: string[]) => [...catalogQueryKeys.all, scopeTypes] as const, +}; + +const NO_SCOPE_TYPES: string[] = []; + +// Requested in the same order as useViewTeamPermissions (libraries first), so both share one +// validate/me query. +const VIEW_TEAM_PERMISSIONS = [SCOPE_TYPES.LIBRARY, SCOPE_TYPES.COURSE].map((scopeType) => ({ + action: VIEW_TEAM_ACTIONS[scopeType], +})); + +/** + * React Query hook to fetch the roles, permissions and categories catalog of the scope types the + * user can view, in a single request. + * + * The scope types come from the user's view-team permissions (validate/me), so the query waits + * for them and is skipped when the user can't view any scope type. `isLoading` covers both. + * The catalog comes from the authz schema and doesn't change while the app runs, so it never + * goes stale. + * + * Besides the query result, it returns: + * - `scopeTypes`: the scope types of the loaded catalog, courses first; empty until it loads. + * - `getScopeCatalog(scopeType)`: the catalog of one scope type (see `getScopeCatalog` in utils), + * or `undefined` if it isn't loaded. Each scope type's catalog keeps its identity between + * renders, so what is memoized from it isn't rebuilt on every render. + * + * @example + * ```tsx + * const { scopeTypes, getScopeCatalog, isLoading } = useAuthzCatalog(); + * const libraryCatalog = getScopeCatalog(SCOPE_TYPES.LIBRARY); + * ``` + */ +export const useAuthzCatalog = () => { + const { + data: permissions, isLoading: isLoadingPermissions, + } = useValidateUserPermissionsNonSuspense(VIEW_TEAM_PERMISSIONS); + + const viewableScopeTypes: string[] = [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY].filter((scopeType) => ( + permissions?.some(({ action, allowed }) => allowed && action === VIEW_TEAM_ACTIONS[scopeType]) + )); + + const query = useQuery({ + queryKey: catalogQueryKeys.byScopeTypes(viewableScopeTypes), + queryFn: () => getAuthzCatalog(viewableScopeTypes), + enabled: viewableScopeTypes.length > 0, + staleTime: Infinity, + }); + + const { data: catalog } = query; + + const scopeCatalogs = useMemo(() => new Map( + (catalog?.scopeTypes ?? []).map((scopeType) => [scopeType, getScopeCatalog(catalog!, scopeType)]), + ), [catalog]); + + const getLoadedScopeCatalog = useCallback( + (scopeType: string) => scopeCatalogs.get(scopeType), + [scopeCatalogs], + ); + + return { + ...query, + isLoading: isLoadingPermissions || query.isLoading, + scopeTypes: catalog?.scopeTypes ?? NO_SCOPE_TYPES, + getScopeCatalog: getLoadedScopeCatalog, + }; +}; diff --git a/src/authz-module/catalog/index.ts b/src/authz-module/catalog/index.ts new file mode 100644 index 00000000..24f1ede1 --- /dev/null +++ b/src/authz-module/catalog/index.ts @@ -0,0 +1,5 @@ +export { useAuthzCatalog } from './data/hooks'; +export { default as CatalogIcon } from './CatalogIcon'; +export type { + AuthzCatalog, Category, CategoryPermissions, Permission, Role, ScopeCatalog, +} from './types'; diff --git a/src/authz-module/catalog/testUtils.ts b/src/authz-module/catalog/testUtils.ts new file mode 100644 index 00000000..a8b0c485 --- /dev/null +++ b/src/authz-module/catalog/testUtils.ts @@ -0,0 +1,110 @@ +/** + * Catalog test helpers: a catalog fixture, builders for it, and a mock of `useAuthzCatalog` serving it. + * + * Suites calling `mockAuthzCatalog` must mock the hook module: + * `jest.mock('@src/authz-module/catalog/data/hooks', () => ({ useAuthzCatalog: jest.fn() }));` + */ +import { SCOPE_TYPES } from '@src/authz-module/constants'; +import { useAuthzCatalog } from './data/hooks'; +import type { + AuthzCatalog, Category, Permission, Role, +} from './types'; +import { getScopeCatalog } from './utils'; + +// Builders of catalog entries: the identifier plus the fields a test cares about; the rest default to +// empty values, and the display name to the identifier. + +export const buildCatalogCategory = (id: string, fields: Partial = {}): Category => ({ + id, displayName: id, description: '', icon: null, ...fields, +}); + +export const buildCatalogPermission = (id: string, fields: Partial = {}): Permission => ({ + id, displayName: id, description: '', icon: null, categoryId: null, scopeTypes: [], ...fields, +}); + +export const buildCatalogRole = (role: string, fields: Partial = {}): Role => ({ + role, displayName: role, description: '', icon: null, definitionKind: 'static', permissions: [], scopeTypes: [], ...fields, +}); + +/** A catalog with the course and library roles. */ +export const authzCatalog: AuthzCatalog = { + scopeTypes: [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY], + categories: [ + buildCatalogCategory('course', { displayName: 'Course', icon: 'BookOpen' }), + buildCatalogCategory('library', { displayName: 'Library', icon: 'CollectionsBookmark' }), + ], + permissions: [ + buildCatalogPermission('content_libraries.edit_library_content', { categoryId: 'library', scopeTypes: [SCOPE_TYPES.LIBRARY] }), + buildCatalogPermission('content_libraries.manage_library_team', { categoryId: 'library', scopeTypes: [SCOPE_TYPES.LIBRARY] }), + buildCatalogPermission('content_libraries.view_library', { categoryId: 'library', scopeTypes: [SCOPE_TYPES.LIBRARY] }), + buildCatalogPermission('courses.edit_course_content', { categoryId: 'course', scopeTypes: [SCOPE_TYPES.COURSE] }), + buildCatalogPermission('courses.manage_course_team', { categoryId: 'course', scopeTypes: [SCOPE_TYPES.COURSE] }), + buildCatalogPermission('courses.view_course', { categoryId: 'course', scopeTypes: [SCOPE_TYPES.COURSE] }), + ], + roles: [ + buildCatalogRole('course_admin', { + displayName: 'Course Admin', + permissions: ['courses.edit_course_content', 'courses.manage_course_team', 'courses.view_course'], + scopeTypes: [SCOPE_TYPES.COURSE], + }), + buildCatalogRole('course_staff', { + displayName: 'Course Staff', + permissions: ['courses.edit_course_content', 'courses.view_course'], + scopeTypes: [SCOPE_TYPES.COURSE], + }), + buildCatalogRole('library_admin', { + displayName: 'Library Admin', + permissions: [ + 'content_libraries.edit_library_content', 'content_libraries.manage_library_team', 'content_libraries.view_library', + ], + scopeTypes: [SCOPE_TYPES.LIBRARY], + }), + buildCatalogRole('library_author', { + displayName: 'Library Author', + permissions: ['content_libraries.edit_library_content', 'content_libraries.view_library'], + scopeTypes: [SCOPE_TYPES.LIBRARY], + }), + buildCatalogRole('library_contributor', { + displayName: 'Library Contributor', + permissions: ['content_libraries.edit_library_content', 'content_libraries.view_library'], + scopeTypes: [SCOPE_TYPES.LIBRARY], + }), + buildCatalogRole('library_user', { + displayName: 'Library User', + permissions: ['content_libraries.view_library'], + scopeTypes: [SCOPE_TYPES.LIBRARY], + }), + ], +}; + +// The part of the `useAuthzCatalog` result its consumers read. +type AuthzCatalogResult = Pick, 'scopeTypes' | 'getScopeCatalog' | 'isLoading' | 'isError'>; + +interface MockAuthzCatalogOptions { + catalog?: AuthzCatalog; + // The scope types the user can view; the catalog's by default. + scopeTypes?: string[]; + isLoading?: boolean; + isError?: boolean; +} + +/** + * Makes `useAuthzCatalog` return `catalog`, limited to the scope types the user can view. Nothing is + * loaded while `isLoading` or on `isError`. Each scope type's catalog is built once, with the real + * `getScopeCatalog`, so it keeps its identity between renders as the hook's does. + */ +export const mockAuthzCatalog = ({ + catalog = authzCatalog, scopeTypes = catalog.scopeTypes, isLoading = false, isError = false, +}: MockAuthzCatalogOptions = {}) => { + const loadedScopeTypes = isLoading || isError ? [] : scopeTypes; + const scopeCatalogs = new Map(loadedScopeTypes.map((scopeType) => [scopeType, getScopeCatalog(catalog, scopeType)])); + + // Typed as the hook's result, so the mock fails to compile if the hook's API changes. + const result: AuthzCatalogResult = { + isLoading, + isError, + scopeTypes: loadedScopeTypes, + getScopeCatalog: (scopeType) => scopeCatalogs.get(scopeType), + }; + (useAuthzCatalog as jest.Mock).mockReturnValue(result); +}; diff --git a/src/authz-module/catalog/types.ts b/src/authz-module/catalog/types.ts new file mode 100644 index 00000000..e19e5690 --- /dev/null +++ b/src/authz-module/catalog/types.ts @@ -0,0 +1,46 @@ +export interface Category { + id: string; + displayName: string; + description: string; + icon: string | null; +} + +export interface Permission { + id: string; + displayName: string; + description: string; + icon: string | null; + categoryId: string | null; + scopeTypes: string[]; +} + +export interface Role { + role: string; + displayName: string; + description: string; + icon: string | null; + definitionKind: 'static' | 'user_defined'; + permissions: string[]; + scopeTypes: string[]; +} + +export interface AuthzCatalog { + scopeTypes: string[]; + categories: Category[]; + permissions: Permission[]; + roles: Role[]; +} + +// A category with some of its permissions. +export interface CategoryPermissions { + category: Category; + permissions: Permission[]; +} + +// The part of the catalog that applies to one scope type. +export interface ScopeCatalog { + scopeType: string; + categories: Category[]; + permissions: Permission[]; + roles: Role[]; +} diff --git a/src/authz-module/catalog/utils.test.ts b/src/authz-module/catalog/utils.test.ts new file mode 100644 index 00000000..8fd05f2d --- /dev/null +++ b/src/authz-module/catalog/utils.test.ts @@ -0,0 +1,88 @@ +import { SCOPE_TYPES } from '@src/authz-module/constants'; +import { buildCatalogCategory, buildCatalogPermission, buildCatalogRole } from './testUtils'; +import type { AuthzCatalog, Role } from './types'; +import { getScopeCatalog, sortRolesByPermissionCount } from './utils'; + +const catalog: AuthzCatalog = { + scopeTypes: [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY], + categories: [buildCatalogCategory('course'), buildCatalogCategory('library'), buildCatalogCategory('team')], + permissions: [ + buildCatalogPermission('courses.view_course', { categoryId: 'course', scopeTypes: [SCOPE_TYPES.COURSE] }), + buildCatalogPermission('courses.edit_course_content', { categoryId: 'course', scopeTypes: [SCOPE_TYPES.COURSE] }), + buildCatalogPermission('content_libraries.view_library', { categoryId: 'library', scopeTypes: [SCOPE_TYPES.LIBRARY] }), + buildCatalogPermission('team.view_team', { + categoryId: 'team', scopeTypes: [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY], + }), + ], + roles: [ + buildCatalogRole('course_staff', { permissions: ['courses.view_course'], scopeTypes: [SCOPE_TYPES.COURSE] }), + buildCatalogRole('course_admin', { + permissions: ['courses.view_course', 'courses.edit_course_content'], scopeTypes: [SCOPE_TYPES.COURSE], + }), + buildCatalogRole('library_user', { + permissions: ['content_libraries.view_library'], scopeTypes: [SCOPE_TYPES.LIBRARY], + }), + buildCatalogRole('team_viewer', { + permissions: ['team.view_team', 'content_libraries.view_library'], + scopeTypes: [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY], + }), + ], +}; + +const roleIds = (roles: Role[]) => roles.map(({ role }) => role); + +describe('getScopeCatalog', () => { + it('keeps only the permissions granted in the scope type', () => { + const { permissions } = getScopeCatalog(catalog, SCOPE_TYPES.LIBRARY); + + expect(permissions.map(({ id }) => id)).toEqual(['content_libraries.view_library', 'team.view_team']); + }); + + it('keeps only the categories used by the scope type permissions', () => { + const { categories } = getScopeCatalog(catalog, SCOPE_TYPES.LIBRARY); + + expect(categories.map(({ id }) => id)).toEqual(['library', 'team']); + }); + + it('leaves out the roles without grants in the scope type', () => { + const { roles } = getScopeCatalog(catalog, SCOPE_TYPES.LIBRARY); + + expect(roleIds(roles)).not.toContain('course_staff'); + expect(roleIds(roles)).not.toContain('course_admin'); + }); + + it('leaves out a role granting a permission of several scope types only in another one', () => { + const courseTeamViewer = buildCatalogRole('course_team_viewer', { + permissions: ['team.view_team'], scopeTypes: [SCOPE_TYPES.COURSE], + }); + const { roles } = getScopeCatalog({ ...catalog, roles: [courseTeamViewer] }, SCOPE_TYPES.LIBRARY); + + expect(roleIds(roles)).toEqual([]); + }); + + it('lists a role spanning several scope types in each, with only that scope type permissions', () => { + const courseRole = getScopeCatalog(catalog, SCOPE_TYPES.COURSE).roles.find(({ role }) => role === 'team_viewer'); + const libraryRole = getScopeCatalog(catalog, SCOPE_TYPES.LIBRARY).roles.find(({ role }) => role === 'team_viewer'); + + expect(courseRole?.permissions).toEqual(['team.view_team']); + expect(libraryRole?.permissions).toEqual(['team.view_team', 'content_libraries.view_library']); + }); + + it('orders the roles from most to fewest permissions in the scope type', () => { + const { roles } = getScopeCatalog(catalog, SCOPE_TYPES.COURSE); + + expect(roleIds(roles)).toEqual(['course_admin', 'course_staff', 'team_viewer']); + }); +}); + +describe('sortRolesByPermissionCount', () => { + it('keeps the catalog order of roles with the same number of permissions', () => { + const roles = [ + buildCatalogRole('b', { displayName: 'Bravo', permissions: ['one'] }), + buildCatalogRole('c', { displayName: 'Charlie', permissions: ['one', 'two'] }), + buildCatalogRole('a', { displayName: 'Alpha', permissions: ['one'] }), + ]; + + expect(roleIds(sortRolesByPermissionCount(roles))).toEqual(['c', 'b', 'a']); + }); +}); diff --git a/src/authz-module/catalog/utils.ts b/src/authz-module/catalog/utils.ts new file mode 100644 index 00000000..ee2d7042 --- /dev/null +++ b/src/authz-module/catalog/utils.ts @@ -0,0 +1,42 @@ +import type { AuthzCatalog, Role, ScopeCatalog } from './types'; + +/** + * Orders roles from the one with most permissions to the one with fewest. Roles with the same + * number of permissions keep their catalog order, so the order does not depend on the language. + */ +export const sortRolesByPermissionCount = (roles: Role[]): Role[] => [...roles].sort((a, b) => ( + b.permissions.length - a.permissions.length +)); + +/** + * Returns the part of the catalog that applies to one scope type. + * + * A role spanning several scope types appears in each of them, listing only the permissions of + * that scope type. + * + * @param catalog - The complete catalog. + * @param scopeType - The scope type to slice (e.g. `course-v1`). + * + * @returns The scope type's catalog: + * - `permissions`: those granted in the scope type, in catalog order. + * - `categories`: those used by the scope type's permissions, in catalog order. + * - `roles`: those with grants in the scope type, holding only its permissions, and ordered from + * most to fewest permissions, ties in catalog order. + */ +export const getScopeCatalog = (catalog: AuthzCatalog, scopeType: string): ScopeCatalog => { + const permissions = catalog.permissions.filter((permission) => permission.scopeTypes.includes(scopeType)); + const permissionIds = new Set(permissions.map(({ id }) => id)); + const categoryIds = new Set(permissions.map(({ categoryId }) => categoryId)); + + const categories = catalog.categories.filter(({ id }) => categoryIds.has(id)); + const roles = catalog.roles + .filter((role) => role.scopeTypes.includes(scopeType)) + .map((role) => ({ ...role, permissions: role.permissions.filter((id) => permissionIds.has(id)) })); + + return { + scopeType, + categories, + permissions, + roles: sortRolesByPermissionCount(roles), + }; +}; diff --git a/src/authz-module/constants.ts b/src/authz-module/constants.ts index 0e6c449e..c9918ba8 100644 --- a/src/authz-module/constants.ts +++ b/src/authz-module/constants.ts @@ -1,3 +1,15 @@ +// Scope types the console supports, as the authz API names them (the namespace of the scope keys). +export const SCOPE_TYPES = { + COURSE: 'course-v1', + LIBRARY: 'lib', +} as const; + +// Permission the user needs to view the teams of each scope type, and so its catalog. +export const VIEW_TEAM_ACTIONS: Record = { + [SCOPE_TYPES.COURSE]: 'courses.view_course_team', + [SCOPE_TYPES.LIBRARY]: 'content_libraries.view_library_team', +}; + // Resource Type Definitions export const CONTEXT_TYPES = { LIBRARY: 'library', From 4437c906878806f19b53c3bbfc97eaa01fe58df9 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Thu, 15 Oct 2026 14:32:20 +1100 Subject: [PATCH 2/7] build: leave the test helpers out of the coverage report and the package Co-Authored-By: Claude Opus 5.5 --- jest.config.js | 1 + tsconfig.build.json | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/jest.config.js b/jest.config.js index b012ae01..bc697654 100644 --- a/jest.config.js +++ b/jest.config.js @@ -10,6 +10,7 @@ module.exports = createConfig('test', { 'src/setupTest.tsx', 'src/i18n', 'src/__mocks__', + 'testUtils', ], moduleNameMapper: { '\\.svg$': '/src/__mocks__/svg.js', diff --git a/tsconfig.build.json b/tsconfig.build.json index 36be1ed1..36747617 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -15,6 +15,7 @@ "src/**/*.spec.tsx", "src/__mocks__/**/*", "src/setupTest.tsx", - "src/testUtils.tsx" + "src/testUtils.tsx", + "src/**/testUtils.ts" ] } From 414487c1aabcbd5e9f2591315c1271ecf607ea38 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Thu, 15 Oct 2026 17:00:06 +1100 Subject: [PATCH 3/7] docs: add an ADR for the AuthZ catalog Co-Authored-By: Claude Opus 5.5 --- docs/decisions/0004-authz-catalog.rst | 158 ++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 docs/decisions/0004-authz-catalog.rst diff --git a/docs/decisions/0004-authz-catalog.rst b/docs/decisions/0004-authz-catalog.rst new file mode 100644 index 00000000..4967d6ee --- /dev/null +++ b/docs/decisions/0004-authz-catalog.rst @@ -0,0 +1,158 @@ +4. AuthZ Catalog as the Source of Roles and Permissions +------------------------------------------------------- + +Status +###### + +Proposed + +Context +####### + +The Admin Console shows the roles and permissions of the authorization system (`openedx-authz`) in several places: + +* the **Roles and Permissions** matrix, which shows which permissions each role grants, grouped by category; +* the **permissions column** of a user's role assignments; +* the **role list** of the assignment wizard; +* the **roles filter** of the assignment tables. + +Until now, every role, permission and category was hardcoded in the frontend (``roles-permissions/course/constants.ts`` and ``roles-permissions/library/constants.ts``), together with their names, descriptions and icons. This copy had to be kept in sync with the backend by hand. A role or permission added to the backend did not appear in the console until the frontend was changed and released, and a mistake in the copy showed users permissions a role does not grant. + +`ADR 0021`_ in `openedx-authz` made the backend the source of truth for this information, and `ADR 0028 - API Contract for the Role and Permission Catalog`_ defined the response of ``GET /api/authz/v1/roles/``. For the requested scope types, one call returns: + +* ``categories``: the categories the permissions are grouped in, with a display name, a description and an icon; +* ``permissions``: every permission, with a display name, a description, an icon, its category and the scope types it supports; +* ``roles``: the roles with grants in the requested scope types, each listing the identifiers of the permissions it grants and the scope types it applies to. + +The response is normalized: a permission is described once and roles only reference it by identifier. Only the roles are paginated; categories and permissions are complete on every page. The endpoint requires the view-team permission of each requested scope type (``courses.view_course_team`` for ``course-v1``, ``content_libraries.view_library_team`` for ``lib``) and answers 403 otherwise. + +Decision +######## + +**1. A dedicated** ``catalog`` **feature owns the catalog.** + +Following `ADR 0002`_, the catalog lives in ``src/authz-module/catalog/``. Its barrel (``index.ts``) exposes only what other features consume: ``useAuthzCatalog``, ``CatalogIcon`` and the catalog types. Screens never call the API or read the raw response. + +:: + + catalog/ + index.ts public API + constants.ts page size + types.ts Category, Permission, Role, AuthzCatalog, ScopeCatalog + utils.ts slicing by scope type and role ordering + CatalogIcon.tsx renders the icon the catalog names + data/api.ts getAuthzCatalog: fetches and merges every page + data/hooks.ts useAuthzCatalog: permissions, query and per-scope-type catalogs + +The scope types the console knows today (``SCOPE_TYPES``: ``course-v1`` and ``lib``) and the view-team action of each one are not catalog data. They stay in ``src/authz-module/constants.ts``, with the rest of what the module knows about scopes, and the catalog imports them from there. They could move to the catalog once the backend informs the scope types (see *Future evolution*). + +**2. The frontend speaks the catalog's vocabulary.** + +The types mirror the API response (camelCased), without adapters to the old hardcoded shapes. Screens move to these types as they are switched over, and the old types are deleted once no screen uses them: + +* a **category** (``id``, ``displayName``) replaces the old "resource"; +* a **permission** (``id``, ``displayName``, ``categoryId``, ``scopeTypes``) replaces the old permission metadata; +* a **role** (``role``, ``displayName``, ``permissions``, ``scopeTypes``) replaces the old role metadata; +* a **scope type** (``course-v1``, ``lib``), the namespace of the scope keys, replaces the old context type (``course``, ``library``). It stays distinct from a **scope**, which is a concrete key such as ``course-v1:OpenedX+DemoX+Demo``. + +**3. One request, for the scope types the user can view.** + +The catalog endpoint answers 403 when the user cannot view the team of a requested scope type. So ``useAuthzCatalog`` first checks the user's view-team permissions through ``/permissions/validate/me``, then requests the catalog of every scope type the user can view, in a single call. A user who cannot view any scope type makes no catalog request. + +The hook takes no arguments, so every consumer shares one cache entry and one request. ``getAuthzCatalog(scopeTypes)`` still takes the scope types, for a caller that needs a subset. + +**4. The whole catalog is loaded and cached for the session.** + +``getAuthzCatalog`` always returns the complete catalog. The API paginates the roles, so it requests the first page with 100 roles, the maximum the API allows. If there are more roles, it requests the remaining pages at the same time and joins their roles in page order. Categories and permissions are not paginated (every page includes all of them), so they are taken from the first page. + +Pages are not loaded on demand, because the current UI displays all the roles of a scope type at once: the matrix shows each role as a column, and the roles filter and the wizard list every role the user can choose. This design fits the limited number of roles per scope type and the scope types known today. + +The catalog comes from the authz schema and does not change while the app runs, so the query has an infinite ``staleTime``. + +**5. Screens consume one scope type at a time.** + +Every screen shows the roles of one scope type at a time (a matrix tab, a filter group, the scope chosen in the wizard, the scope of an assignment). ``getScopeCatalog(scopeType)`` returns that part of the catalog: + +* **permissions**: those whose ``scopeTypes`` include the scope type; +* **categories**: those used by those permissions; +* **roles**: those whose ``scopeTypes`` include the scope type, each listing only its permissions of that scope type, ordered from most to fewest permissions. Roles with the same count keep the catalog order, so the order does not depend on the language. + +Roles and permissions each keep their own ``scopeTypes`` because the catalog of every viewable scope type comes in one response, and each screen picks the part of its scope type: the roles by their ``scopeTypes`` and the permissions by theirs. + +The hook memoizes each scope type's catalog, so its identity is stable between renders and the screens can memoize what they build from it, such as the matrix and the roles filter choices, without rebuilding it on every render. + +**6. Icons are rendered by name, downloading only the ones used.** + +The catalog names Paragon icons (for example ``RemoveRedEye``). ``CatalogIcon`` lazy-imports ``@openedx/paragon/icons/es5/.js``, keeping one ``React.lazy`` component per name, so only the icons the catalog names are downloaded and an icon added in the backend works without a frontend change. While an icon loads, or when its name is unknown, it renders an empty icon of the same size, so the layout does not shift. When the catalog sends no icon, it renders nothing. + +Webpack emits one small chunk per Paragon icon. ``es5/index.js``, which re-exports every icon, is excluded so it never becomes a chunk. + +**7. The catalog describes; it does not authorize.** + +``/permissions/validate/me`` stays the only source of what the user can do. The catalog only describes which roles and permissions exist and what each role grants. + +Some screens check a specific permission before showing an action, for example whether the user can manage a course team before showing the button to assign roles. The names of those permissions are constants in the frontend, not read from the catalog, because each one is tied to a specific action in the UI. + +Consequences +############ + +* Roles, permissions, categories, names, descriptions and icons added or changed in the backend appear in the console without a frontend release. +* The console only shows what the catalog returns. Roles that the hardcoded copy listed as disabled no longer appear until the backend returns them. +* Names and descriptions come from the backend and are not translated by the frontend. +* Screens depend on one more request. Until the catalog loads, they show their loading state. +* The frontend still knows the scope types it supports (``SCOPE_TYPES`` in ``authz-module/constants.ts``), the view-team action of each one and their display order (courses, then libraries). A new scope type still needs a frontend change (see *Future evolution*). + +Rejected Alternatives +##################### + +**Keep the hardcoded copy, synchronized by hand** + This is the situation the catalog replaces: two sources of truth that drift. + +**Adapt the catalog to the old hardcoded shapes** + It would let screens keep their code, but it would keep two vocabularies (resource and category, context type and scope type) and an adapter layer to maintain. Moving each screen to the catalog types once is simpler. + +**Request the catalog per screen or per scope type** + Each screen would compute its own scope types, different lists would make separate requests, and a wrong list would answer 403. One request for every viewable scope type, sliced on the client, is shared by every screen. + +**Map icon names to components in the frontend** + A static map would bundle every mapped icon and need a frontend change for each new icon, which reintroduces the copy the catalog removes. + +Future evolution +################ + +**Scope-type agnostic frontend.** The goal is a frontend that does not know the scope types, so a scope type defined in the backend (for example by a plugin, see the extensibility section of `ADR 0028`_) appears without frontend changes. What is still hardcoded: + +* the view-team action of each scope type, used to build the request; +* ``SCOPE_TYPES`` and their display order; +* the tab labels, filter group names and group icons; +* the manage-team action of each scope type, used by the wizard. + +A possible backend evolution: + +1. Make ``scope_types`` optional in the request. Without it, the endpoint returns the catalog of every scope type the user can view and leaves out the others instead of answering 403. +2. Return the scope types as objects whose order is the display order, carrying their display name, description, icon, and view and manage permissions. + +With that, ``useAuthzCatalog`` keeps its signature but makes one query without parameters and no longer waits for validate/me. The matrix tabs and filter groups come from the response, the wizard checks each scope type's manage permission through validate/me, and the scope types come from the catalog instead of ``SCOPE_TYPES`` and the view-team mapping in ``authz-module/constants.ts``. Because a scope type id is the prefix of its scope keys, the icons and labels of scopes could also come from the catalog. + +For that step: + +* The manage permission would be catalog data, and the frontend would still check it through validate/me, which remains the source for any behavior the UI displays. +* The tab labels and group names are translated in the frontend today, while the backend display names are English only. Moving them to the catalog would expect the backend to translate the scope type information as well. + +**Loading on demand.** The current UI displays all the roles of a scope type at once (Decision 4). Loading the roles on demand, with search or paging in the UI instead of showing every role at once, is only worth it if real cases show that the number of roles per scope type has grown too large for that, for example with user-defined roles. Until then, the current approach stays. + +**User-defined roles.** The types already carry ``definitionKind`` (``static`` or ``user_defined``). Roles are expected to be defined in the backend only, so the console just displays them. If screens to create or edit roles are ever added to the console, they would invalidate the catalog query after a change, since its ``staleTime`` is infinite. + +**Display order.** The backend returns categories, permissions and roles in a stable order by identifier, and explicit display ordering is a backend follow-up. The frontend keeps the API order for categories and permissions, so a backend display order applies without a frontend change. Roles are ordered by permission count in the frontend, which could move to the backend as well. + +References +########## + +* `ADR 0002`_ — feature-based application organization +* `ADR 0021`_ — the authz model as the source of truth for authorization definitions +* `ADR 0028 - API Contract for the Role and Permission Catalog`_ + +.. _ADR 0002: ./0002-feature-based-application-organization.rst +.. _ADR 0021: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0021-authorization-definition-api.rst +.. _ADR 0028: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0028-api-contract-for-role-catalog.rst +.. _ADR 0028 - API Contract for the Role and Permission Catalog: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0028-api-contract-for-role-catalog.rst From c4a4ab27f774edef81fe825912374628857038d8 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Wed, 28 Oct 2026 17:09:14 +1100 Subject: [PATCH 4/7] refactor: use frontend-base usePermissions --- src/authz-module/catalog/data/hooks.test.tsx | 70 ++++++++++++++------ src/authz-module/catalog/data/hooks.ts | 20 +++--- 2 files changed, 59 insertions(+), 31 deletions(-) diff --git a/src/authz-module/catalog/data/hooks.test.tsx b/src/authz-module/catalog/data/hooks.test.tsx index d8211f2f..a7672631 100644 --- a/src/authz-module/catalog/data/hooks.test.tsx +++ b/src/authz-module/catalog/data/hooks.test.tsx @@ -1,4 +1,5 @@ import { renderHook, waitFor } from '@testing-library/react'; +import { usePermissions } from '@openedx/frontend-base'; import { createQueryClientWrapper, mockHttpClient } from '@src/testUtils'; import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; import { CATALOG_PAGE_SIZE } from '../constants'; @@ -7,12 +8,14 @@ import { useAuthzCatalog } from './hooks'; jest.mock('@openedx/frontend-base', () => ({ ...jest.requireActual('@openedx/frontend-base'), getAuthenticatedHttpClient: jest.fn(), + usePermissions: jest.fn(), })); -interface MockApiOptions { +interface MockPermissionsOptions { course?: boolean; library?: boolean; isPermissionsPending?: boolean; + isPermissionsError?: boolean; } const buildPermission = (id: string, scopeType: string) => ({ @@ -23,15 +26,21 @@ const buildRole = (role: string, permissions: string[], scopeType: string) => ({ role, display_name: role, description: '', icon: null, definition_kind: 'static', permissions, scope_types: [scopeType], }); -// Answers validate/me with the given view-team permissions, and the catalog endpoint with a -// course role and a library role, for the scope types that were requested. -const mockApi = ({ course = false, library = false, isPermissionsPending = false }: MockApiOptions) => { - const post = jest.fn(() => (isPermissionsPending ? new Promise(() => {}) : Promise.resolve({ - data: [ - { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.COURSE], allowed: course }, - { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.LIBRARY], allowed: library }, - ], - }))); +const mockPermissions = ({ + course = false, library = false, isPermissionsPending = false, isPermissionsError = false, +}: MockPermissionsOptions = {}) => { + jest.mocked(usePermissions>).mockReturnValue({ + [SCOPE_TYPES.COURSE]: course, + [SCOPE_TYPES.LIBRARY]: library, + isLoading: isPermissionsPending, + isError: isPermissionsError, + isPaused: false, + error: isPermissionsError ? new Error('Permission validation failed') : null, + isAuthzEnabled: true, + }); +}; + +const mockCatalogApi = () => { const get = jest.fn((url: URL) => Promise.resolve({ data: { count: 0, @@ -49,8 +58,8 @@ const mockApi = ({ course = false, library = false, isPermissionsPending = false ], }, })); - mockHttpClient().mockReturnValue({ get, post }); - return { get, post }; + mockHttpClient().mockReturnValue({ get }); + return { get }; }; const renderUseAuthzCatalog = () => renderHook(() => useAuthzCatalog(), { wrapper: createQueryClientWrapper() }); @@ -61,15 +70,21 @@ describe('useAuthzCatalog', () => { }); it('fetches the catalog of every scope type the user can view', async () => { - mockApi({ course: true, library: true }); + mockPermissions({ course: true, library: true }); + mockCatalogApi(); const { result } = renderUseAuthzCatalog(); await waitFor(() => expect(result.current.scopeTypes).toEqual([SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY])); + expect(usePermissions).toHaveBeenCalledWith({ + [SCOPE_TYPES.COURSE]: { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.COURSE] }, + [SCOPE_TYPES.LIBRARY]: { action: VIEW_TEAM_ACTIONS[SCOPE_TYPES.LIBRARY] }, + }, true); }); it('fetches only the library catalog when the user can only view library teams', async () => { - mockApi({ library: true }); + mockPermissions({ library: true }); + mockCatalogApi(); const { result } = renderUseAuthzCatalog(); @@ -77,7 +92,8 @@ describe('useAuthzCatalog', () => { }); it('gives the catalog of each scope type the user can view', async () => { - mockApi({ course: true, library: true }); + mockPermissions({ course: true, library: true }); + mockCatalogApi(); const { result } = renderUseAuthzCatalog(); @@ -88,7 +104,8 @@ describe('useAuthzCatalog', () => { }); it('keeps the same scope type catalog between renders', async () => { - mockApi({ library: true }); + mockPermissions({ library: true }); + mockCatalogApi(); const { result, rerender } = renderUseAuthzCatalog(); await waitFor(() => expect(result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)).toBeDefined()); @@ -100,7 +117,8 @@ describe('useAuthzCatalog', () => { }); it('is loading while the view permissions are being resolved', () => { - const { get } = mockApi({ isPermissionsPending: true }); + mockPermissions({ isPermissionsPending: true }); + const { get } = mockCatalogApi(); const { result } = renderUseAuthzCatalog(); @@ -109,7 +127,8 @@ describe('useAuthzCatalog', () => { }); it('does not fetch a catalog when the user cannot view any team', async () => { - const { get } = mockApi({}); + mockPermissions(); + const { get } = mockCatalogApi(); const { result } = renderUseAuthzCatalog(); @@ -119,8 +138,19 @@ describe('useAuthzCatalog', () => { expect(get).not.toHaveBeenCalled(); }); + it('exposes permission validation errors without fetching the catalog', () => { + mockPermissions({ isPermissionsError: true }); + const { get } = mockCatalogApi(); + + const { result } = renderUseAuthzCatalog(); + + expect(result.current.isError).toBe(true); + expect(result.current.error?.message).toBe('Permission validation failed'); + expect(get).not.toHaveBeenCalled(); + }); + it('lists the roles of every page, in order, when they do not fit in one page', async () => { - const { post } = mockApi({ library: true }); + mockPermissions({ library: true }); // Three pages of roles, one role in each. const get = jest.fn((url: URL) => { const page = Number(url.searchParams.get('page')); @@ -138,7 +168,7 @@ describe('useAuthzCatalog', () => { }, }); }); - mockHttpClient().mockReturnValue({ get, post }); + mockHttpClient().mockReturnValue({ get }); const { result } = renderUseAuthzCatalog(); diff --git a/src/authz-module/catalog/data/hooks.ts b/src/authz-module/catalog/data/hooks.ts index a319f913..fc312e72 100644 --- a/src/authz-module/catalog/data/hooks.ts +++ b/src/authz-module/catalog/data/hooks.ts @@ -1,7 +1,7 @@ import { useCallback, useMemo } from 'react'; import { useQuery } from '@tanstack/react-query'; +import { usePermissions } from '@openedx/frontend-base'; import { appId } from '@src/constants'; -import { useValidateUserPermissionsNonSuspense } from '@src/data/hooks'; import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; import { getAuthzCatalog } from './api'; import type { AuthzCatalog, ScopeCatalog } from '../types'; @@ -14,11 +14,9 @@ const catalogQueryKeys = { const NO_SCOPE_TYPES: string[] = []; -// Requested in the same order as useViewTeamPermissions (libraries first), so both share one -// validate/me query. -const VIEW_TEAM_PERMISSIONS = [SCOPE_TYPES.LIBRARY, SCOPE_TYPES.COURSE].map((scopeType) => ({ - action: VIEW_TEAM_ACTIONS[scopeType], -})); +const VIEW_TEAM_PERMISSIONS = Object.fromEntries( + Object.entries(VIEW_TEAM_ACTIONS).map(([scopeType, action]) => [scopeType, { action }]), +); /** * React Query hook to fetch the roles, permissions and categories catalog of the scope types the @@ -42,12 +40,10 @@ const VIEW_TEAM_PERMISSIONS = [SCOPE_TYPES.LIBRARY, SCOPE_TYPES.COURSE].map((sco * ``` */ export const useAuthzCatalog = () => { - const { - data: permissions, isLoading: isLoadingPermissions, - } = useValidateUserPermissionsNonSuspense(VIEW_TEAM_PERMISSIONS); + const permissions = usePermissions(VIEW_TEAM_PERMISSIONS, true); const viewableScopeTypes: string[] = [SCOPE_TYPES.COURSE, SCOPE_TYPES.LIBRARY].filter((scopeType) => ( - permissions?.some(({ action, allowed }) => allowed && action === VIEW_TEAM_ACTIONS[scopeType]) + permissions[scopeType] === true )); const query = useQuery({ @@ -70,7 +66,9 @@ export const useAuthzCatalog = () => { return { ...query, - isLoading: isLoadingPermissions || query.isLoading, + isLoading: permissions.isLoading || query.isLoading, + isError: permissions.isError || query.isError, + error: permissions.error ?? query.error, scopeTypes: catalog?.scopeTypes ?? NO_SCOPE_TYPES, getScopeCatalog: getLoadedScopeCatalog, }; From ee7d4ae22b7707bbf806af18c8989cf46d17bf53 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Wed, 28 Oct 2026 17:10:09 +1100 Subject: [PATCH 5/7] docs: make cleared a future scope type metadata --- docs/decisions/0004-authz-catalog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions/0004-authz-catalog.rst b/docs/decisions/0004-authz-catalog.rst index 4967d6ee..dc619c3c 100644 --- a/docs/decisions/0004-authz-catalog.rst +++ b/docs/decisions/0004-authz-catalog.rst @@ -57,7 +57,7 @@ The types mirror the API response (camelCased), without adapters to the old hard **3. One request, for the scope types the user can view.** -The catalog endpoint answers 403 when the user cannot view the team of a requested scope type. So ``useAuthzCatalog`` first checks the user's view-team permissions through ``/permissions/validate/me``, then requests the catalog of every scope type the user can view, in a single call. A user who cannot view any scope type makes no catalog request. +The catalog endpoint answers 403 when the user cannot view the team of a requested scope type. So ``useAuthzCatalog`` first checks the user's view-team permissions with ``usePermissions`` from ``@openedx/frontend-base`` (which calls ``/permissions/validate/me``), then requests the catalog of every scope type the user can view, in a single call. A user who cannot view any scope type makes no catalog request. The hook takes no arguments, so every consumer shares one cache entry and one request. ``getAuthzCatalog(scopeTypes)`` still takes the scope types, for a caller that needs a subset. @@ -137,7 +137,7 @@ With that, ``useAuthzCatalog`` keeps its signature but makes one query without p For that step: * The manage permission would be catalog data, and the frontend would still check it through validate/me, which remains the source for any behavior the UI displays. -* The tab labels and group names are translated in the frontend today, while the backend display names are English only. Moving them to the catalog would expect the backend to translate the scope type information as well. +* Tab labels and group names are translated in the frontend today. Moving them to the catalog would require the backend to provide localized scope-type metadata, alongside the localized role, permission and category metadata it already returns. **Loading on demand.** The current UI displays all the roles of a scope type at once (Decision 4). Loading the roles on demand, with search or paging in the UI instead of showing every role at once, is only worth it if real cases show that the number of roles per scope type has grown too large for that, for example with user-defined roles. Until then, the current approach stays. From c62ea0aef646f3cf060d073c5894460bf6318406 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Wed, 28 Oct 2026 17:39:52 +1100 Subject: [PATCH 6/7] docs: update ADR to reflect icon set agreedment --- docs/decisions/0004-authz-catalog.rst | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/decisions/0004-authz-catalog.rst b/docs/decisions/0004-authz-catalog.rst index dc619c3c..8c3ae5d6 100644 --- a/docs/decisions/0004-authz-catalog.rst +++ b/docs/decisions/0004-authz-catalog.rst @@ -81,11 +81,15 @@ Roles and permissions each keep their own ``scopeTypes`` because the catalog of The hook memoizes each scope type's catalog, so its identity is stable between renders and the screens can memoize what they build from it, such as the matrix and the roles filter choices, without rebuilding it on every render. -**6. Icons are rendered by name, downloading only the ones used.** +**6. CatalogIcon owns the mapping from catalog identifiers to icons.** -The catalog names Paragon icons (for example ``RemoveRedEye``). ``CatalogIcon`` lazy-imports ``@openedx/paragon/icons/es5/.js``, keeping one ``React.lazy`` component per name, so only the icons the catalog names are downloaded and an icon added in the backend works without a frontend change. While an icon loads, or when its name is unknown, it renders an empty icon of the same size, so the layout does not shift. When the catalog sends no icon, it renders nothing. +The backend and frontend will agree on a supported set of icon identifiers, independent of Paragon's exported names. The frontend will map each identifier to an available icon component. This keeps the catalog contract independent of the icon library and version selected by the downstream site. See the `backend icon contract discussion`_. The identifier set and its mappings have not been finalized yet. -Webpack emits one small chunk per Paragon icon. ``es5/index.js``, which re-exports every icon, is excluded so it never becomes a chunk. +Consumers pass the catalog's icon identifier to ```` without interpreting it or importing the corresponding icon themselves. The component preserves an empty icon of the same size for unknown identifiers and renders nothing when the catalog sends no icon. + +**Temporary implementation.** ``CatalogIcon`` currently accepts Paragon icon names and lazy-imports ``@openedx/paragon/icons/es5/.js``, with one ``React.lazy`` component per name. While an icon loads, it renders the same empty placeholder. Webpack emits one small chunk per Paragon icon and excludes ``es5/index.js`` from those chunks. + +Once the identifier set is agreed, the explicit frontend map will replace dynamic imports. The public ``name`` prop and fallback behavior remain unchanged, so consumers remain independent of how icons are resolved. **7. The catalog describes; it does not authorize.** @@ -96,7 +100,7 @@ Some screens check a specific permission before showing an action, for example w Consequences ############ -* Roles, permissions, categories, names, descriptions and icons added or changed in the backend appear in the console without a frontend release. +* Roles, permissions, categories, names and descriptions added or changed in the backend appear in catalog consumers without a frontend release. They can use any supported icon identifier; adding a new identifier requires agreement on the contract and an update to the frontend map. * The console only shows what the catalog returns. Roles that the hardcoded copy listed as disabled no longer appear until the backend returns them. * Names and descriptions come from the backend and are not translated by the frontend. * Screens depend on one more request. Until the catalog loads, they show their loading state. @@ -114,8 +118,8 @@ Rejected Alternatives **Request the catalog per screen or per scope type** Each screen would compute its own scope types, different lists would make separate requests, and a wrong list would answer 403. One request for every viewable scope type, sliced on the client, is shared by every screen. -**Map icon names to components in the frontend** - A static map would bundle every mapped icon and need a frontend change for each new icon, which reintroduces the copy the catalog removes. +**Use Paragon export names as the permanent icon contract** + This couples backend schemas to the icon library and version selected by each downstream site. Dynamic imports remain a temporary implementation; the intended contract is an agreed set of identifiers mapped to components by the frontend (Decision 6). Future evolution ################ @@ -156,3 +160,5 @@ References .. _ADR 0021: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0021-authorization-definition-api.rst .. _ADR 0028: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0028-api-contract-for-role-catalog.rst .. _ADR 0028 - API Contract for the Role and Permission Catalog: https://github.com/openedx/openedx-authz/blob/main/docs/decisions/0028-api-contract-for-role-catalog.rst + +.. _backend icon contract discussion: https://github.com/openedx/openedx-authz/pull/537#issuecomment-6425395515 From 18d66571f10e3cdb1fde5d9667940f8154b08f26 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Tue, 10 Nov 2026 13:37:35 +1100 Subject: [PATCH 7/7] fix(authz): refresh catalog data and clarify catalog ADR --- docs/decisions/0004-authz-catalog.rst | 45 +++++----- src/authz-module/catalog/data/hooks.test.tsx | 89 +++++++++++++++++++- src/authz-module/catalog/data/hooks.ts | 30 +++++-- src/authz-module/catalog/index.ts | 2 +- 4 files changed, 134 insertions(+), 32 deletions(-) diff --git a/docs/decisions/0004-authz-catalog.rst b/docs/decisions/0004-authz-catalog.rst index 8c3ae5d6..9c75ea44 100644 --- a/docs/decisions/0004-authz-catalog.rst +++ b/docs/decisions/0004-authz-catalog.rst @@ -31,7 +31,7 @@ Decision **1. A dedicated** ``catalog`` **feature owns the catalog.** -Following `ADR 0002`_, the catalog lives in ``src/authz-module/catalog/``. Its barrel (``index.ts``) exposes only what other features consume: ``useAuthzCatalog``, ``CatalogIcon`` and the catalog types. Screens never call the API or read the raw response. +Following `ADR 0002`_, the catalog lives in ``src/authz-module/catalog/``. Its barrel (``index.ts``) exposes only what other features consume: ``useAuthzCatalog``, ``invalidateAuthzCatalog``, ``CatalogIcon`` and the catalog types. Screens never call the API or read the raw response. :: @@ -55,30 +55,30 @@ The types mirror the API response (camelCased), without adapters to the old hard * a **role** (``role``, ``displayName``, ``permissions``, ``scopeTypes``) replaces the old role metadata; * a **scope type** (``course-v1``, ``lib``), the namespace of the scope keys, replaces the old context type (``course``, ``library``). It stays distinct from a **scope**, which is a concrete key such as ``course-v1:OpenedX+DemoX+Demo``. -**3. One request, for the scope types the user can view.** +**3. One shared catalog for the scope types the user can view.** -The catalog endpoint answers 403 when the user cannot view the team of a requested scope type. So ``useAuthzCatalog`` first checks the user's view-team permissions with ``usePermissions`` from ``@openedx/frontend-base`` (which calls ``/permissions/validate/me``), then requests the catalog of every scope type the user can view, in a single call. A user who cannot view any scope type makes no catalog request. +The catalog endpoint answers 403 when the user cannot view the team of a requested scope type. So ``useAuthzCatalog`` first checks the user's view-team permissions with ``usePermissions`` from ``@openedx/frontend-base`` (which calls ``/permissions/validate/me``), then loads the catalog for all viewable scope types together. A user who cannot view any scope type makes no catalog request. -The hook takes no arguments, so every consumer shares one cache entry and one request. ``getAuthzCatalog(scopeTypes)`` still takes the scope types, for a caller that needs a subset. +The hook takes no arguments; consumers share the cached catalog for the user's viewable scope types. ``getAuthzCatalog(scopeTypes)`` still takes the scope types, for a caller that needs a subset. -**4. The whole catalog is loaded and cached for the session.** +**4. The whole catalog is loaded and shared through the cache.** -``getAuthzCatalog`` always returns the complete catalog. The API paginates the roles, so it requests the first page with 100 roles, the maximum the API allows. If there are more roles, it requests the remaining pages at the same time and joins their roles in page order. Categories and permissions are not paginated (every page includes all of them), so they are taken from the first page. +``getAuthzCatalog`` always returns the complete catalog for the requested scope types. The API paginates the roles, so it requests the first page with 100 roles, the maximum the API allows. If there are more roles, it requests the remaining pages at the same time and joins their roles in page order. Categories and permissions are not paginated (every page includes all of them), so they are taken from the first page. Pages are not loaded on demand, because the current UI displays all the roles of a scope type at once: the matrix shows each role as a column, and the roles filter and the wizard list every role the user can choose. This design fits the limited number of roles per scope type and the scope types known today. -The catalog comes from the authz schema and does not change while the app runs, so the query has an infinite ``staleTime``. +The catalog uses a thirty-minute ``staleTime`` to balance reuse across consumers with freshness as role definitions become editable. -**5. Screens consume one scope type at a time.** +Role-definition mutations should call ``invalidateAuthzCatalog(queryClient)`` after success, keeping query keys private to the catalog feature. Assigning or revoking an existing role does not change its definition and does not require catalog invalidation. -Every screen shows the roles of one scope type at a time (a matrix tab, a filter group, the scope chosen in the wizard, the scope of an assignment). ``getScopeCatalog(scopeType)`` returns that part of the catalog: +**5. Current consumers derive scope-specific views.** + +The current UI derives scope-specific views from the shared catalog: a matrix tab, a role-filter section, the scope chosen in the wizard, or an assignment's permission breakdown. A screen can combine views of several scope types, as the roles filter does. ``getScopeCatalog(scopeType)`` returns that part of the catalog: * **permissions**: those whose ``scopeTypes`` include the scope type; * **categories**: those used by those permissions; * **roles**: those whose ``scopeTypes`` include the scope type, each listing only its permissions of that scope type, ordered from most to fewest permissions. Roles with the same count keep the catalog order, so the order does not depend on the language. -Roles and permissions each keep their own ``scopeTypes`` because the catalog of every viewable scope type comes in one response, and each screen picks the part of its scope type: the roles by their ``scopeTypes`` and the permissions by theirs. - The hook memoizes each scope type's catalog, so its identity is stable between renders and the screens can memoize what they build from it, such as the matrix and the roles filter choices, without rebuilding it on every render. **6. CatalogIcon owns the mapping from catalog identifiers to icons.** @@ -103,7 +103,7 @@ Consequences * Roles, permissions, categories, names and descriptions added or changed in the backend appear in catalog consumers without a frontend release. They can use any supported icon identifier; adding a new identifier requires agreement on the contract and an update to the frontend map. * The console only shows what the catalog returns. Roles that the hardcoded copy listed as disabled no longer appear until the backend returns them. * Names and descriptions come from the backend and are not translated by the frontend. -* Screens depend on one more request. Until the catalog loads, they show their loading state. +* Screens depend on loading the catalog. Until it loads, they show their loading state. * The frontend still knows the scope types it supports (``SCOPE_TYPES`` in ``authz-module/constants.ts``), the view-team action of each one and their display order (courses, then libraries). A new scope type still needs a frontend change (see *Future evolution*). Rejected Alternatives @@ -116,7 +116,7 @@ Rejected Alternatives It would let screens keep their code, but it would keep two vocabularies (resource and category, context type and scope type) and an adapter layer to maintain. Moving each screen to the catalog types once is simpler. **Request the catalog per screen or per scope type** - Each screen would compute its own scope types, different lists would make separate requests, and a wrong list would answer 403. One request for every viewable scope type, sliced on the client, is shared by every screen. + Each screen would compute its own scope types, different lists would make separate requests, and a wrong list would answer 403. Sharing the catalog for all viewable scope types avoids this duplication; consumers derive their views from it. **Use Paragon export names as the permanent icon contract** This couples backend schemas to the icon library and version selected by each downstream site. Dynamic imports remain a temporary implementation; the intended contract is an agreed set of identifiers mapped to components by the frontend (Decision 6). @@ -124,28 +124,27 @@ Rejected Alternatives Future evolution ################ -**Scope-type agnostic frontend.** The goal is a frontend that does not know the scope types, so a scope type defined in the backend (for example by a plugin, see the extensibility section of `ADR 0028`_) appears without frontend changes. What is still hardcoded: +**Backend-provided scope-type metadata.** Moving scope-type metadata to the backend could allow new scope types (for example, those defined by a plugin; see the extensibility section of `ADR 0028`_) to appear without frontend changes. Whether that flexibility justifies the additional API and frontend complexity remains an open decision. The frontend currently defines: * the view-team action of each scope type, used to build the request; -* ``SCOPE_TYPES`` and their display order; -* the tab labels, filter group names and group icons; +* the scope-type keys (``SCOPE_TYPES``) and their display order; +* the scope-type presentation metadata: the "Courses" and "Libraries" tab labels, role-filter section labels, their translations, and icons; * the manage-team action of each scope type, used by the wizard. -A possible backend evolution: +Adding a new scope type therefore requires frontend changes. Role-filter sections group roles by scope type; catalog categories group permissions. + +If this approach is adopted, the backend should: 1. Make ``scope_types`` optional in the request. Without it, the endpoint returns the catalog of every scope type the user can view and leaves out the others instead of answering 403. 2. Return the scope types as objects whose order is the display order, carrying their display name, description, icon, and view and manage permissions. -With that, ``useAuthzCatalog`` keeps its signature but makes one query without parameters and no longer waits for validate/me. The matrix tabs and filter groups come from the response, the wizard checks each scope type's manage permission through validate/me, and the scope types come from the catalog instead of ``SCOPE_TYPES`` and the view-team mapping in ``authz-module/constants.ts``. Because a scope type id is the prefix of its scope keys, the icons and labels of scopes could also come from the catalog. - -For that step: +The frontend should then use this metadata to build matrix tabs, role-filter sections and permission mappings. ``useAuthzCatalog`` could keep its signature, fetching the catalog without ``scope_types`` and without first calling validate/me. Manage permissions would still be checked through validate/me. -* The manage permission would be catalog data, and the frontend would still check it through validate/me, which remains the source for any behavior the UI displays. -* Tab labels and group names are translated in the frontend today. Moving them to the catalog would require the backend to provide localized scope-type metadata, alongside the localized role, permission and category metadata it already returns. +The backend would also need to localize the scope-type labels currently translated in the frontend. **Loading on demand.** The current UI displays all the roles of a scope type at once (Decision 4). Loading the roles on demand, with search or paging in the UI instead of showing every role at once, is only worth it if real cases show that the number of roles per scope type has grown too large for that, for example with user-defined roles. Until then, the current approach stays. -**User-defined roles.** The types already carry ``definitionKind`` (``static`` or ``user_defined``). Roles are expected to be defined in the backend only, so the console just displays them. If screens to create or edit roles are ever added to the console, they would invalidate the catalog query after a change, since its ``staleTime`` is infinite. +**User-defined roles.** The catalog types already distinguish ``static`` and ``user_defined`` roles through ``definitionKind``. Future role-management screens may also need to refresh affected role assignments after permission edits or role deletions. **Display order.** The backend returns categories, permissions and roles in a stable order by identifier, and explicit display ordering is a backend follow-up. The frontend keeps the API order for categories and permissions, so a backend display order applies without a frontend change. Roles are ordered by permission count in the frontend, which could move to the backend as well. diff --git a/src/authz-module/catalog/data/hooks.test.tsx b/src/authz-module/catalog/data/hooks.test.tsx index a7672631..3c2960e6 100644 --- a/src/authz-module/catalog/data/hooks.test.tsx +++ b/src/authz-module/catalog/data/hooks.test.tsx @@ -1,9 +1,10 @@ -import { renderHook, waitFor } from '@testing-library/react'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClient } from '@tanstack/react-query'; import { usePermissions } from '@openedx/frontend-base'; import { createQueryClientWrapper, mockHttpClient } from '@src/testUtils'; import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; import { CATALOG_PAGE_SIZE } from '../constants'; -import { useAuthzCatalog } from './hooks'; +import { invalidateAuthzCatalog, useAuthzCatalog } from './hooks'; jest.mock('@openedx/frontend-base', () => ({ ...jest.requireActual('@openedx/frontend-base'), @@ -69,6 +70,90 @@ describe('useAuthzCatalog', () => { jest.clearAllMocks(); }); + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('reuses fresh catalog data when another consumer mounts', async () => { + mockPermissions({ library: true }); + const { get } = mockCatalogApi(); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const wrapper = createQueryClientWrapper(queryClient); + const first = renderHook(() => useAuthzCatalog(), { wrapper }); + await waitFor(() => expect(first.result.current.isSuccess).toBe(true)); + + jest.spyOn(Date, 'now').mockReturnValue(first.result.current.dataUpdatedAt + 30 * 60 * 1000 - 1); + const second = renderHook(() => useAuthzCatalog(), { wrapper }); + + expect(second.result.current.data).toBe(first.result.current.data); + expect(second.result.current.isFetching).toBe(false); + expect(get).toHaveBeenCalledTimes(1); + }); + + it('refreshes the catalog on mount after thirty minutes', async () => { + mockPermissions({ library: true }); + const { get } = mockCatalogApi(); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const wrapper = createQueryClientWrapper(queryClient); + const first = renderHook(() => useAuthzCatalog(), { wrapper }); + await waitFor(() => expect(first.result.current.isSuccess).toBe(true)); + first.unmount(); + + jest.spyOn(Date, 'now').mockReturnValue(first.result.current.dataUpdatedAt + 30 * 60 * 1000 + 1); + const second = renderHook(() => useAuthzCatalog(), { wrapper }); + + await waitFor(() => expect(get).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(second.result.current.isFetching).toBe(false)); + }); + + it('refreshes an active catalog immediately when explicitly invalidated', async () => { + mockPermissions({ library: true }); + const { get } = mockCatalogApi(); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const { result } = renderHook(() => useAuthzCatalog(), { + wrapper: createQueryClientWrapper(queryClient), + }); + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + get.mockResolvedValueOnce({ + data: { + count: 1, + next: null, + previous: null, + scope_types: [SCOPE_TYPES.LIBRARY], + categories: [], + permissions: [], + results: [buildRole('custom_role', [], SCOPE_TYPES.LIBRARY)], + }, + }); + + await act(async () => invalidateAuthzCatalog(queryClient)); + + expect(get).toHaveBeenCalledTimes(2); + await waitFor(() => expect( + result.current.getScopeCatalog(SCOPE_TYPES.LIBRARY)?.roles.map(({ role }) => role), + ).toEqual(['custom_role'])); + }); + + it('invalidates every cached scope combination without touching unrelated queries', async () => { + mockCatalogApi(); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const wrapper = createQueryClientWrapper(queryClient); + for (const scopes of [{ course: true }, { library: true }, { course: true, library: true }]) { + mockPermissions(scopes); + const { result, unmount } = renderHook(() => useAuthzCatalog(), { wrapper }); + await waitFor(() => expect(result.current.isSuccess).toBe(true)); + unmount(); + } + const catalogQueries = queryClient.getQueryCache().getAll(); + expect(catalogQueries).toHaveLength(3); + queryClient.setQueryData(['unrelated'], 'cached data'); + + await invalidateAuthzCatalog(queryClient); + + expect(catalogQueries.every((query) => query.state.isInvalidated)).toBe(true); + expect(queryClient.getQueryState(['unrelated'])?.isInvalidated).toBe(false); + }); + it('fetches the catalog of every scope type the user can view', async () => { mockPermissions({ course: true, library: true }); mockCatalogApi(); diff --git a/src/authz-module/catalog/data/hooks.ts b/src/authz-module/catalog/data/hooks.ts index fc312e72..ccbd1672 100644 --- a/src/authz-module/catalog/data/hooks.ts +++ b/src/authz-module/catalog/data/hooks.ts @@ -1,5 +1,5 @@ import { useCallback, useMemo } from 'react'; -import { useQuery } from '@tanstack/react-query'; +import { QueryClient, useQuery } from '@tanstack/react-query'; import { usePermissions } from '@openedx/frontend-base'; import { appId } from '@src/constants'; import { SCOPE_TYPES, VIEW_TEAM_ACTIONS } from '@src/authz-module/constants'; @@ -12,6 +12,26 @@ const catalogQueryKeys = { byScopeTypes: (scopeTypes: string[]) => [...catalogQueryKeys.all, scopeTypes] as const, }; +/** + * Invalidate the catalog of every scope combination after a successful role-definition change. + * + * @example + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query'; + * import { invalidateAuthzCatalog } from '@src/authz-module/catalog'; + * + * // Inside a hook that updates role definitions: + * const queryClient = useQueryClient(); + * const mutation = useMutation({ + * mutationFn: updateRoleDefinition, + * onSuccess: () => invalidateAuthzCatalog(queryClient), + * }); + * ``` + */ +export const invalidateAuthzCatalog = (queryClient: QueryClient) => queryClient.invalidateQueries({ + queryKey: catalogQueryKeys.all, +}); + const NO_SCOPE_TYPES: string[] = []; const VIEW_TEAM_PERMISSIONS = Object.fromEntries( @@ -19,13 +39,11 @@ const VIEW_TEAM_PERMISSIONS = Object.fromEntries( ); /** - * React Query hook to fetch the roles, permissions and categories catalog of the scope types the - * user can view, in a single request. + * Loads the shared roles, permissions and categories catalog for the scope types the user can view. * * The scope types come from the user's view-team permissions (validate/me), so the query waits * for them and is skipped when the user can't view any scope type. `isLoading` covers both. - * The catalog comes from the authz schema and doesn't change while the app runs, so it never - * goes stale. + * The catalog stays fresh for thirty minutes. * * Besides the query result, it returns: * - `scopeTypes`: the scope types of the loaded catalog, courses first; empty until it loads. @@ -50,7 +68,7 @@ export const useAuthzCatalog = () => { queryKey: catalogQueryKeys.byScopeTypes(viewableScopeTypes), queryFn: () => getAuthzCatalog(viewableScopeTypes), enabled: viewableScopeTypes.length > 0, - staleTime: Infinity, + staleTime: 30 * 60 * 1000, }); const { data: catalog } = query; diff --git a/src/authz-module/catalog/index.ts b/src/authz-module/catalog/index.ts index 24f1ede1..f569debd 100644 --- a/src/authz-module/catalog/index.ts +++ b/src/authz-module/catalog/index.ts @@ -1,4 +1,4 @@ -export { useAuthzCatalog } from './data/hooks'; +export { useAuthzCatalog, invalidateAuthzCatalog } from './data/hooks'; export { default as CatalogIcon } from './CatalogIcon'; export type { AuthzCatalog, Category, CategoryPermissions, Permission, Role, ScopeCatalog,