From 3782081af3ee13b1237f95d6857bd81acc92424f Mon Sep 17 00:00:00 2001 From: Brayan Ceron Date: Fri, 22 May 2026 16:34:21 -0500 Subject: [PATCH 01/11] feat: implement permission validation API and hooks for authz --- docs/how_tos/permissions.md | 147 +++++++++++++++++++++++++++++++++++ runtime/authz/api.test.ts | 80 +++++++++++++++++++ runtime/authz/api.ts | 54 +++++++++++++ runtime/authz/hooks.test.tsx | 105 +++++++++++++++++++++++++ runtime/authz/hooks.ts | 87 +++++++++++++++++++++ runtime/authz/index.ts | 3 + runtime/authz/types.ts | 27 +++++++ runtime/index.ts | 2 + 8 files changed, 505 insertions(+) create mode 100644 docs/how_tos/permissions.md create mode 100644 runtime/authz/api.test.ts create mode 100644 runtime/authz/api.ts create mode 100644 runtime/authz/hooks.test.tsx create mode 100644 runtime/authz/hooks.ts create mode 100644 runtime/authz/index.ts create mode 100644 runtime/authz/types.ts diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md new file mode 100644 index 00000000..0e75275f --- /dev/null +++ b/docs/how_tos/permissions.md @@ -0,0 +1,147 @@ +# How to: Query Permissions from openedx-authz + +## Overview + +`@openedx/frontend-base` provides hooks and utilities to validate user permissions against the +`openedx-authz` service. Results are cached automatically via TanStack Query to minimize calls +to the backend. + +## Prerequisites + +Ensure your app root is wrapped with a `QueryClientProvider` from `@tanstack/react-query`. + +--- + +## Core Concepts + +### Permission query shape + +Permissions are expressed as a key/value map where: +- **keys** are arbitrary semantic names you choose (e.g. `canEditGrading`) +- **values** describe the `action` string and optional `scope` (resource identifier) + +```typescript +import type { PermissionValidationQuery } from '@openedx/frontend-base'; + +const query: PermissionValidationQuery = { + canViewGrading: { + action: 'courses.view_grading_settings', + scope: 'course-v1:org+course+run', + }, + canEditGrading: { + action: 'courses.edit_grading_settings', + scope: 'course-v1:org+course+run', + }, +}; +``` + +### Caching + +Results are cached using TanStack Query. The cache key includes the query object and the +resolved `apiBaseUrl`, so different backends and different permission sets are cached +independently. Results are reused across components that request the same permissions within +one session. + +--- + +## `usePermissions` + +The single hook for querying permissions. Requires a `featureEnabled` boolean — always +pass the resolved waffle flag value so the caller explicitly opts in or out of authz. +Permission keys are spread at the top level — no nested `.permissions` object. + +```typescript +import { usePermissions } from '@openedx/frontend-base'; +import { getConfig } from '@edx/frontend-platform'; + +// featureEnabled is required — always pass the resolved waffle flag boolean: +const { enableAuthz } = useWaffleFlags(resourceId); +const { isLoading, isAuthzEnabled, canViewGrading, canEditGrading } = usePermissions( + { + canViewGrading: { action: 'courses.view_grading_settings', scope: resourceId }, + canEditGrading: { action: 'courses.edit_grading_settings', scope: resourceId }, + }, + enableAuthz ?? false, +); + +// Override the backend URL (e.g. MFEs using @edx/frontend-platform): +const { isLoading, canViewGrading } = usePermissions( + { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId } }, + enableAuthz ?? false, + { apiBaseUrl: getConfig().LMS_BASE_URL }, +); + +if (!canViewGrading) { return ; } +``` + +When `featureEnabled` is `false`: no API call is made and all keys return `true`, +preserving the pre-authz behavior during rollout. + +--- + +## Recommended: create an MFE-specific wrapper + +Avoid calling `usePermissions` directly in every component. Create a single MFE-level +wrapper that encapsulates the waffle flag check and base URL: + +```typescript +import { usePermissions } from '@openedx/frontend-base'; +import { getConfig } from '@edx/frontend-platform'; +import { useWaffleFlags } from './waffleHooks'; // your MFE's waffle flag hook +import type { PermissionValidationQuery } from '@openedx/frontend-base'; + +export const useResourcePermissions = ( + resourceId: string, + permissions: Query, +) => { + const { enableAuthz } = useWaffleFlags(resourceId); + return usePermissions( + permissions, + enableAuthz ?? false, + { apiBaseUrl: getConfig().LMS_BASE_URL }, + ); +}; + +export const getResourcePermissions = (resourceId: string): PermissionValidationQuery => ({ + canView: { action: 'resources.view', scope: resourceId }, + canEdit: { action: 'resources.edit', scope: resourceId }, +}); + +// Usage in any component: +const { isLoading, canView, canEdit } = + useResourcePermissions(resourceId, getResourcePermissions(resourceId)); +``` + +--- + +## Best Practices + +- **Define permission constants** in your MFE (`COURSE_PERMISSIONS`, etc.) rather than + inline strings — prevents typos and makes global renames easy. +- **Use query builder helpers** (`getGradingPermissions(courseId)`) to build the query + object — keeps permission definitions co-located with the feature they belong to. +- **Do not duplicate `{ action, scope }` pairs** within a single query — only the first + matching key is mapped in the response. +- **Keep `featureEnabled` close to the flag source** — the boolean should come directly + from your waffle flag check, not be stored in state or passed through many layers. + +--- + +## Manual Cache Invalidation + +If user roles change mid-session and you need to force a refetch: + +```typescript +import { permissionsQueryKeys } from '@openedx/frontend-base'; +import { getConfig } from '@edx/frontend-platform'; + +// Default — URL comes from getSiteConfig().lmsBaseUrl (set via mergeSiteConfig): +queryClient.invalidateQueries({ + queryKey: permissionsQueryKeys.validate(myQuery), +}); + +// Explicit URL — use when you passed apiBaseUrl in UsePermissionsOptions: +queryClient.invalidateQueries({ + queryKey: permissionsQueryKeys.validate(myQuery, getConfig().LMS_BASE_URL), +}); +``` diff --git a/runtime/authz/api.test.ts b/runtime/authz/api.test.ts new file mode 100644 index 00000000..fe33cbc1 --- /dev/null +++ b/runtime/authz/api.test.ts @@ -0,0 +1,80 @@ +import { getAuthenticatedHttpClient } from '../auth'; +import { validatePermissions, PERMISSIONS_VALIDATE_PATH } from './api'; + +jest.mock('../auth', () => ({ + getAuthenticatedHttpClient: jest.fn(), +})); + +const BASE_URL = 'http://lms.example.com'; +const QUERY = { + canRead: { action: 'example.read', scope: 'lib:org:test' }, + canWrite: { action: 'example.write', scope: 'lib:org:test' }, +}; + +describe('validatePermissions', () => { + beforeEach(() => jest.clearAllMocks()); + + it('posts to the correct URL', async () => { + const postMock = jest.fn().mockResolvedValue({ data: [] }); + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ post: postMock }); + + await validatePermissions(BASE_URL, QUERY); + + expect(postMock).toHaveBeenCalledWith( + `${BASE_URL}${PERMISSIONS_VALIDATE_PATH}`, + expect.any(Array), + ); + }); + + it('sends all query items as an array in the request body', async () => { + const postMock = jest.fn().mockResolvedValue({ data: [] }); + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ post: postMock }); + + await validatePermissions(BASE_URL, QUERY); + + const body = postMock.mock.calls[0][1]; + expect(body).toHaveLength(2); + expect(body).toEqual(expect.arrayContaining([ + { action: 'example.read', scope: 'lib:org:test' }, + { action: 'example.write', scope: 'lib:org:test' }, + ])); + }); + + it('maps response array back to caller keys', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ + data: [ + { action: 'example.read', scope: 'lib:org:test', allowed: true }, + { action: 'example.write', scope: 'lib:org:test', allowed: false }, + ], + }), + }); + + const result = await validatePermissions(BASE_URL, QUERY); + + expect(result).toEqual({ canRead: true, canWrite: false }); + }); + + it('defaults missing keys to false', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ data: [] }), + }); + + const result = await validatePermissions(BASE_URL, QUERY); + + expect(result).toEqual({ canRead: false, canWrite: false }); + }); + + it('defaults a partially missing key to false', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ + data: [{ action: 'example.read', scope: 'lib:org:test', allowed: true }], + }), + }); + + const result = await validatePermissions(BASE_URL, QUERY); + + expect(result.canRead).toBe(true); + expect(result.canWrite).toBe(false); + }); +}); diff --git a/runtime/authz/api.ts b/runtime/authz/api.ts new file mode 100644 index 00000000..fac3b654 --- /dev/null +++ b/runtime/authz/api.ts @@ -0,0 +1,54 @@ +import { getAuthenticatedHttpClient } from '../auth'; +import type { + PermissionValidationQuery, + PermissionValidationAnswer, + PermissionValidationRequestItem, + PermissionValidationResponseItem, +} from './types'; + +export const PERMISSIONS_VALIDATE_PATH = '/api/authz/v1/permissions/validate/me'; + +/** + * Validates whether the currently authenticated user holds the requested permissions + * against the openedx-authz backend. + * + * @param apiBaseUrl - Base URL of the backend running openedx-authz (e.g. getConfig().LMS_BASE_URL). + * @param query - Key/value map of permission check descriptors. + * @returns Map of the same keys to boolean allowed values. + * Any key absent from the server response resolves to false. + * + * Known limitation: if two entries in the query share identical { action, scope }, + * only the first matching key is mapped. Do not duplicate { action, scope } pairs. + */ +export const validatePermissions = async ( + apiBaseUrl: string, + query: Query, +): Promise> => { + const request: PermissionValidationRequestItem[] = Object.values(query); + + const { data }: { data: PermissionValidationResponseItem[] } + = await getAuthenticatedHttpClient().post( + `${apiBaseUrl}${PERMISSIONS_VALIDATE_PATH}`, + request, + ); + + const result = {} as PermissionValidationAnswer; + + data.forEach((item) => { + const key = Object.keys(query).find( + (k) => query[k].action === item.action && query[k].scope === item.scope, + ) as keyof Query | undefined; + if (key !== undefined) { + result[key] = item.allowed; + } + }); + + // Default any key absent from the server response to false + (Object.keys(query) as (keyof Query)[]).forEach((key) => { + if (!(key in result)) { + result[key] = false; + } + }); + + return result; +}; diff --git a/runtime/authz/hooks.test.tsx b/runtime/authz/hooks.test.tsx new file mode 100644 index 00000000..11415eef --- /dev/null +++ b/runtime/authz/hooks.test.tsx @@ -0,0 +1,105 @@ +import React from 'react'; +import { renderHook, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { getAuthenticatedHttpClient } from '../auth'; +import { usePermissions, permissionsQueryKeys } from './hooks'; + +jest.mock('../auth', () => ({ + getAuthenticatedHttpClient: jest.fn(), +})); + +const BASE_URL = 'http://lms.example.com'; +const QUERY = { + canView: { action: 'courses.view_grading_settings', scope: 'course-v1:org+course+run' }, + canEdit: { action: 'courses.edit_grading_settings', scope: 'course-v1:org+course+run' }, +}; + +const createWrapper = () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return ({ children }: { children: React.ReactNode }) => ( + {children} + ); +}; + +describe('usePermissions', () => { + beforeEach(() => jest.clearAllMocks()); + + it('returns actual server values when featureEnabled is true', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ + data: [ + { action: 'courses.view_grading_settings', scope: 'course-v1:org+course+run', allowed: true }, + { action: 'courses.edit_grading_settings', scope: 'course-v1:org+course+run', allowed: false }, + ], + }), + }); + + const { result } = renderHook( + () => usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect(result.current.canView).toBe(true); + expect(result.current.canEdit).toBe(false); + expect(result.current.isAuthzEnabled).toBe(true); + }); + + it('returns all keys as true and makes no API call when featureEnabled is false', () => { + const postMock = jest.fn(); + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ post: postMock }); + + const { result } = renderHook( + () => usePermissions(QUERY, false, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + + expect(postMock).not.toHaveBeenCalled(); + expect(result.current.canView).toBe(true); + expect(result.current.canEdit).toBe(true); + expect(result.current.isLoading).toBe(false); + expect(result.current.isAuthzEnabled).toBe(false); + }); + + it('defaults absent server keys to false when featureEnabled is true', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ data: [] }), + }); + + const { result } = renderHook( + () => usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect(result.current.canView).toBe(false); + expect(result.current.canEdit).toBe(false); + }); + + it('spreads permission keys at the top level — no nested .permissions object', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockResolvedValue({ + data: [ + { action: 'courses.view_grading_settings', scope: 'course-v1:org+course+run', allowed: true }, + ], + }), + }); + + const { result } = renderHook( + () => usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect('canView' in result.current).toBe(true); + expect('permissions' in result.current).toBe(false); + }); + + it('scopes cache by apiBaseUrl — different base URLs produce distinct query keys', () => { + const keyA = permissionsQueryKeys.validate(QUERY, 'http://lms-a.example.com'); + const keyB = permissionsQueryKeys.validate(QUERY, 'http://lms-b.example.com'); + expect(keyA).not.toEqual(keyB); + }); +}); diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts new file mode 100644 index 00000000..20ad6f37 --- /dev/null +++ b/runtime/authz/hooks.ts @@ -0,0 +1,87 @@ +import { skipToken, useQuery } from '@tanstack/react-query'; +import { getSiteConfig } from '../config'; +import type { PermissionValidationQuery, PermissionValidationAnswer } from './types'; +import { validatePermissions } from './api'; + +export const permissionsQueryKeys = { + all: ['authz'] as const, + validate: (query: PermissionValidationQuery, apiBaseUrl: string = getSiteConfig().lmsBaseUrl) => + [...permissionsQueryKeys.all, 'validatePermissions', apiBaseUrl, query] as const, +}; + +export interface UsePermissionsOptions { + /** Default false — authz returns definitive answers; retrying 403s wastes requests. */ + retry?: boolean | number, + /** + * Base URL of the backend running openedx-authz. + * Defaults to getSiteConfig().lmsBaseUrl when omitted. + * Pass explicitly when the authz service requires a different backend (e.g. Studio). + */ + apiBaseUrl?: string, +} + +/** + * Intersection return type: metadata fields plus every permission key spread at the top level. + * Consumers destructure permission keys directly, no nested from `permissions.*` object. + * + * @example + * const { isLoading, canViewGradingSettings, canEditGradingSettings } = + * usePermissions(query, featureEnabled); + */ +export type UsePermissionsResult = { + isLoading: boolean, + isAuthzEnabled: boolean, +} & PermissionValidationAnswer; + +/** + * Queries the openedx-authz service for the given permissions. + * + * When featureEnabled is false: no API call is made; all permission keys return true, + * preserving the pre-authz behavior during gradual rollout. + * When featureEnabled is true: hits the authz API; returns actual server values. + * + * The caller is responsible for reading its own waffle flag and passing the result + * as featureEnabled — waffle flag differ per MFE + * + * @param query - Key/value map of permission check descriptors. + * @param featureEnabled - Pass the result of your waffle flag check here. + * @param options - Optional retry and apiBaseUrl settings. + * + * @example + * const { enableAuthzCourseAuthoring } = useWaffleFlags(courseId); + * const { isLoading, canViewGrading, canEditGrading } = usePermissions( + * { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId }, + * canEditGrading: { action: 'courses.edit_grading_settings', scope: courseId } }, + * enableAuthzCourseAuthoring ?? false, + * { apiBaseUrl: getConfig().LMS_BASE_URL }, + * ); + */ +export const usePermissions = ( + query: Query, + featureEnabled: boolean, + options: UsePermissionsOptions = {}, +): UsePermissionsResult => { + const { retry = false, apiBaseUrl = getSiteConfig().lmsBaseUrl } = options; + + const { isLoading, data } = useQuery, Error>({ + queryKey: permissionsQueryKeys.validate(query, apiBaseUrl), + queryFn: featureEnabled ? () => validatePermissions(apiBaseUrl, query) : skipToken, + retry, + }); + + const permissionResults = isLoading + ? ({} as PermissionValidationAnswer) + : (Object.keys(query) as (keyof Query)[]).reduce( + (acc, key) => { + acc[key] = featureEnabled ? (data?.[key] ?? false) : true; + return acc; + }, + {} as PermissionValidationAnswer, + ); + + return { + isLoading: featureEnabled ? isLoading : false, + isAuthzEnabled: featureEnabled, + ...permissionResults, + } as UsePermissionsResult; +}; diff --git a/runtime/authz/index.ts b/runtime/authz/index.ts new file mode 100644 index 00000000..f31dfd21 --- /dev/null +++ b/runtime/authz/index.ts @@ -0,0 +1,3 @@ +export { usePermissions, permissionsQueryKeys } from './hooks'; +export type { UsePermissionsOptions, UsePermissionsResult } from './hooks'; +export type { PermissionValidationQuery, PermissionValidationAnswer } from './types'; diff --git a/runtime/authz/types.ts b/runtime/authz/types.ts new file mode 100644 index 00000000..7ae5f7a6 --- /dev/null +++ b/runtime/authz/types.ts @@ -0,0 +1,27 @@ +export interface PermissionValidationRequestItem { + action: string; + scope?: string; +} + +export interface PermissionValidationResponseItem extends PermissionValidationRequestItem { + allowed: boolean; +} + +export interface PermissionValidationQuery { + [permissionKey: string]: PermissionValidationRequestItem; +} + +/** + * Maps each key from the caller's query to a boolean allowed value. + * The generic form preserves exact key names for autocomplete and typo detection. + * Use the default (non-generic) form when the query shape is not statically known. + * + * @example + * const query = { canEdit: { action: 'courses.edit' } } satisfies PermissionValidationQuery; + * const answer: PermissionValidationAnswer = { canEdit: true }; + */ +export type PermissionValidationAnswer< + Query extends PermissionValidationQuery = PermissionValidationQuery, +> = { + [K in keyof Query]: boolean; +}; diff --git a/runtime/index.ts b/runtime/index.ts index c21c801d..9c23e6e0 100644 --- a/runtime/index.ts +++ b/runtime/index.ts @@ -145,3 +145,5 @@ export { } from './utils'; export * from './slots'; + +export * from './authz'; From b87e6d29e3a741ade1fdc45969ef33cbb8355133 Mon Sep 17 00:00:00 2001 From: Brayan Ceron Date: Fri, 22 May 2026 16:56:53 -0500 Subject: [PATCH 02/11] feat: enhance usePermissions hook with error handling and loading states --- docs/how_tos/permissions.md | 29 +++++++++++++++++++++-------- runtime/authz/hooks.test.tsx | 35 +++++++++++++++++++++++++++++++++++ runtime/authz/hooks.ts | 25 ++++++++++++++++++++----- 3 files changed, 76 insertions(+), 13 deletions(-) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index 0e75275f..1380d474 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -52,11 +52,10 @@ Permission keys are spread at the top level — no nested `.permissions` object. ```typescript import { usePermissions } from '@openedx/frontend-base'; -import { getConfig } from '@edx/frontend-platform'; // featureEnabled is required — always pass the resolved waffle flag boolean: const { enableAuthz } = useWaffleFlags(resourceId); -const { isLoading, isAuthzEnabled, canViewGrading, canEditGrading } = usePermissions( +const { isLoading, isError, isAuthzEnabled, canViewGrading, canEditGrading } = usePermissions( { canViewGrading: { action: 'courses.view_grading_settings', scope: resourceId }, canEditGrading: { action: 'courses.edit_grading_settings', scope: resourceId }, @@ -64,18 +63,32 @@ const { isLoading, isAuthzEnabled, canViewGrading, canEditGrading } = usePermiss enableAuthz ?? false, ); -// Override the backend URL (e.g. MFEs using @edx/frontend-platform): -const { isLoading, canViewGrading } = usePermissions( +if (isLoading) { return ; } +if (isError) { return ; } +if (!canViewGrading) { return ; } +``` + +When `featureEnabled` is `false`: no API call is made and all keys return `true`, +preserving the pre-authz behavior during rollout. + +To override the backend URL (e.g. MFEs using `@edx/frontend-platform`), pass `apiBaseUrl` +in the options argument: + +```typescript +import { usePermissions } from '@openedx/frontend-base'; +import { getConfig } from '@edx/frontend-platform'; + +const { enableAuthz } = useWaffleFlags(courseId); +const { isLoading, isError, canViewGrading } = usePermissions( { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId } }, enableAuthz ?? false, { apiBaseUrl: getConfig().LMS_BASE_URL }, ); - -if (!canViewGrading) { return ; } ``` -When `featureEnabled` is `false`: no API call is made and all keys return `true`, -preserving the pre-authz behavior during rollout. +> **Service unavailability:** if the authz API call fails, `isError` is `true` and all +> permission keys resolve to `false`. Always check `isLoading` and `isError` before +> rendering gated UI to avoid incorrectly denying access during transient failures. --- diff --git a/runtime/authz/hooks.test.tsx b/runtime/authz/hooks.test.tsx index 11415eef..7a4f4b7d 100644 --- a/runtime/authz/hooks.test.tsx +++ b/runtime/authz/hooks.test.tsx @@ -45,6 +45,7 @@ describe('usePermissions', () => { expect(result.current.canView).toBe(true); expect(result.current.canEdit).toBe(false); expect(result.current.isAuthzEnabled).toBe(true); + expect(result.current.isError).toBe(false); }); it('returns all keys as true and makes no API call when featureEnabled is false', () => { @@ -60,6 +61,7 @@ describe('usePermissions', () => { expect(result.current.canView).toBe(true); expect(result.current.canEdit).toBe(true); expect(result.current.isLoading).toBe(false); + expect(result.current.isError).toBe(false); expect(result.current.isAuthzEnabled).toBe(false); }); @@ -97,6 +99,39 @@ describe('usePermissions', () => { expect('permissions' in result.current).toBe(false); }); + it('returns undefined permission keys and isLoading=true while the API call is in flight', async () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn(() => new Promise(() => {})), // never resolves + }); + + const { result } = renderHook( + () => usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + + expect(result.current.isLoading).toBe(true); + expect(result.current.canView).toBeUndefined(); + expect(result.current.canEdit).toBeUndefined(); + }); + + it('sets isError=true and defaults all keys to false when the API call fails', async () => { + jest.spyOn(console, 'error').mockImplementation(() => {}); + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn().mockRejectedValue(new Error('network error')), + }); + + const { result } = renderHook( + () => usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + { wrapper: createWrapper() }, + ); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect(result.current.isError).toBe(true); + expect(result.current.canView).toBe(false); + expect(result.current.canEdit).toBe(false); + jest.restoreAllMocks(); + }); + it('scopes cache by apiBaseUrl — different base URLs produce distinct query keys', () => { const keyA = permissionsQueryKeys.validate(QUERY, 'http://lms-a.example.com'); const keyB = permissionsQueryKeys.validate(QUERY, 'http://lms-b.example.com'); diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index 20ad6f37..1fd06164 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -3,6 +3,14 @@ import { getSiteConfig } from '../config'; import type { PermissionValidationQuery, PermissionValidationAnswer } from './types'; import { validatePermissions } from './api'; +/** + * TanStack Query cache key factory for permission queries. + * Use `validate` to scope cache reads and invalidations to a specific + * query + backend combination. + * + * @example + * queryClient.invalidateQueries({ queryKey: permissionsQueryKeys.validate(myQuery) }); + */ export const permissionsQueryKeys = { all: ['authz'] as const, validate: (query: PermissionValidationQuery, apiBaseUrl: string = getSiteConfig().lmsBaseUrl) => @@ -22,14 +30,20 @@ export interface UsePermissionsOptions { /** * Intersection return type: metadata fields plus every permission key spread at the top level. - * Consumers destructure permission keys directly, no nested from `permissions.*` object. + * Consumers destructure permission keys directly — no nested `.permissions` object. * * @example - * const { isLoading, canViewGradingSettings, canEditGradingSettings } = - * usePermissions(query, featureEnabled); + * const { enableAuthz } = useWaffleFlags(courseId); + * const { isLoading, isError, canViewGrading, canEditGrading } = usePermissions( + * { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId }, + * canEditGrading: { action: 'courses.edit_grading_settings', scope: courseId } }, + * enableAuthz ?? false, + * { apiBaseUrl: getConfig().LMS_BASE_URL }, + * ); */ export type UsePermissionsResult = { isLoading: boolean, + isError: boolean, isAuthzEnabled: boolean, } & PermissionValidationAnswer; @@ -41,7 +55,7 @@ export type UsePermissionsResult = { * When featureEnabled is true: hits the authz API; returns actual server values. * * The caller is responsible for reading its own waffle flag and passing the result - * as featureEnabled — waffle flag differ per MFE + * as featureEnabled — waffle flag names differ per MFE * * @param query - Key/value map of permission check descriptors. * @param featureEnabled - Pass the result of your waffle flag check here. @@ -63,7 +77,7 @@ export const usePermissions = ( ): UsePermissionsResult => { const { retry = false, apiBaseUrl = getSiteConfig().lmsBaseUrl } = options; - const { isLoading, data } = useQuery, Error>({ + const { isLoading, isError, data } = useQuery, Error>({ queryKey: permissionsQueryKeys.validate(query, apiBaseUrl), queryFn: featureEnabled ? () => validatePermissions(apiBaseUrl, query) : skipToken, retry, @@ -81,6 +95,7 @@ export const usePermissions = ( return { isLoading: featureEnabled ? isLoading : false, + isError: featureEnabled ? isError : false, isAuthzEnabled: featureEnabled, ...permissionResults, } as UsePermissionsResult; From da5419758eba17b89626287451b18778cc133f1c Mon Sep 17 00:00:00 2001 From: Brayan Ceron Date: Fri, 22 May 2026 17:24:44 -0500 Subject: [PATCH 03/11] refactor: simplify permission validation logic and update types for clarity --- runtime/authz/api.ts | 25 ++++++------------------- runtime/authz/hooks.ts | 2 +- runtime/authz/types.ts | 10 ++++------ 3 files changed, 11 insertions(+), 26 deletions(-) diff --git a/runtime/authz/api.ts b/runtime/authz/api.ts index fac3b654..0f843faf 100644 --- a/runtime/authz/api.ts +++ b/runtime/authz/api.ts @@ -16,9 +16,6 @@ export const PERMISSIONS_VALIDATE_PATH = '/api/authz/v1/permissions/validate/me' * @param query - Key/value map of permission check descriptors. * @returns Map of the same keys to boolean allowed values. * Any key absent from the server response resolves to false. - * - * Known limitation: if two entries in the query share identical { action, scope }, - * only the first matching key is mapped. Do not duplicate { action, scope } pairs. */ export const validatePermissions = async ( apiBaseUrl: string, @@ -34,21 +31,11 @@ export const validatePermissions = async ; - data.forEach((item) => { - const key = Object.keys(query).find( - (k) => query[k].action === item.action && query[k].scope === item.scope, - ) as keyof Query | undefined; - if (key !== undefined) { - result[key] = item.allowed; - } - }); - - // Default any key absent from the server response to false - (Object.keys(query) as (keyof Query)[]).forEach((key) => { - if (!(key in result)) { - result[key] = false; - } - }); - + for (const [key, reqItem] of Object.entries(query) as [keyof Query, PermissionValidationRequestItem][]) { + const match = data.find( + (item) => item.action === reqItem.action && item.scope === reqItem.scope, + ); + result[key] = match ? match.allowed : false; + } return result; }; diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index 1fd06164..d8bbbeb8 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -45,7 +45,7 @@ export type UsePermissionsResult = { isLoading: boolean, isError: boolean, isAuthzEnabled: boolean, -} & PermissionValidationAnswer; +} & { [K in keyof Query]: boolean | undefined }; /** * Queries the openedx-authz service for the given permissions. diff --git a/runtime/authz/types.ts b/runtime/authz/types.ts index 7ae5f7a6..cd9d6cfa 100644 --- a/runtime/authz/types.ts +++ b/runtime/authz/types.ts @@ -1,15 +1,13 @@ export interface PermissionValidationRequestItem { - action: string; - scope?: string; + action: string, + scope?: string, } export interface PermissionValidationResponseItem extends PermissionValidationRequestItem { - allowed: boolean; + allowed: boolean, } -export interface PermissionValidationQuery { - [permissionKey: string]: PermissionValidationRequestItem; -} +export type PermissionValidationQuery = Record; /** * Maps each key from the caller's query to a boolean allowed value. From 65c607f02a4176d71d8059e2e29ba355883fb123 Mon Sep 17 00:00:00 2001 From: Brayan Ceron Date: Tue, 26 May 2026 18:50:38 -0500 Subject: [PATCH 04/11] refactor: address feedback --- runtime/authz/hooks.ts | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index d8bbbeb8..0f2b303f 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -26,6 +26,12 @@ export interface UsePermissionsOptions { * Pass explicitly when the authz service requires a different backend (e.g. Studio). */ apiBaseUrl?: string, + /** + * How long (in ms) the cached result is considered fresh before TanStack Query refetches. + * Defaults to 5 minutes. Use permissionsQueryKeys to invalidate manually when user roles + * change mid-session. + */ + staleTime?: number, } /** @@ -52,14 +58,18 @@ export type UsePermissionsResult = { * * When featureEnabled is false: no API call is made; all permission keys return true, * preserving the pre-authz behavior during gradual rollout. - * When featureEnabled is true: hits the authz API; returns actual server values. + * When featureEnabled is true: posts to the authz API and maps each key in the query + * to the allowed boolean from the server response. Keys absent from the response default + * to false. Keys are undefined while the request is in flight (check isLoading first). * - * The caller is responsible for reading its own waffle flag and passing the result - * as featureEnabled — waffle flag names differ per MFE + * The caller is responsible for reading its own waffle flag and passing the resolved + * boolean as featureEnabled. The hook is agnostic to how that boolean was derived — + * whether from a global flag, a per-course override, or a per-org override, the behavior + * is the same. Waffle flag names differ per MFE. * * @param query - Key/value map of permission check descriptors. * @param featureEnabled - Pass the result of your waffle flag check here. - * @param options - Optional retry and apiBaseUrl settings. + * @param options - Optional retry, apiBaseUrl, and staleTime settings. * * @example * const { enableAuthzCourseAuthoring } = useWaffleFlags(courseId); @@ -75,12 +85,18 @@ export const usePermissions = ( featureEnabled: boolean, options: UsePermissionsOptions = {}, ): UsePermissionsResult => { - const { retry = false, apiBaseUrl = getSiteConfig().lmsBaseUrl } = options; + const { + retry = false, + apiBaseUrl = getSiteConfig().lmsBaseUrl, + // staleTime defaults to 5 min + staleTime = 5 * 60 * 1000 + } = options; const { isLoading, isError, data } = useQuery, Error>({ queryKey: permissionsQueryKeys.validate(query, apiBaseUrl), queryFn: featureEnabled ? () => validatePermissions(apiBaseUrl, query) : skipToken, retry, + staleTime, }); const permissionResults = isLoading From 0198af6295e29bbefa43f8389ceb32569e79f41d Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Thu, 20 Aug 2026 14:20:50 +1000 Subject: [PATCH 05/11] docs: add link to permissions documentation --- docs/how_tos/permissions.md | 4 ++++ runtime/authz/hooks.ts | 3 +++ 2 files changed, 7 insertions(+) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index 1380d474..f1344564 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -20,6 +20,10 @@ Permissions are expressed as a key/value map where: - **keys** are arbitrary semantic names you choose (e.g. `canEditGrading`) - **values** describe the `action` string and optional `scope` (resource identifier) +To find the available permissions you can use, see the +[Core Roles and Permissions](https://docs.openedx.org/projects/openedx-authz/en/latest/concepts/core_roles_and_permissions/index.html) +reference in the openedx-authz documentation. + ```typescript import type { PermissionValidationQuery } from '@openedx/frontend-base'; diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index 0f2b303f..fc92d1d0 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -67,6 +67,9 @@ export type UsePermissionsResult = { * whether from a global flag, a per-course override, or a per-org override, the behavior * is the same. Waffle flag names differ per MFE. * + * See https://docs.openedx.org/projects/openedx-authz/en/latest/concepts/core_roles_and_permissions/index.html + * for the available permission you can query. + * * @param query - Key/value map of permission check descriptors. * @param featureEnabled - Pass the result of your waffle flag check here. * @param options - Optional retry, apiBaseUrl, and staleTime settings. From 6e44220eec00681b252ab2a95a2f3f8ae8992334 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 21 Aug 2026 08:38:18 +1000 Subject: [PATCH 06/11] docs: remove frontend-platoform references --- docs/how_tos/permissions.md | 19 ++++++++----------- runtime/authz/api.ts | 2 +- runtime/authz/hooks.ts | 4 ++-- 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index f1344564..80184eb4 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -75,18 +75,17 @@ if (!canViewGrading) { return ; } When `featureEnabled` is `false`: no API call is made and all keys return `true`, preserving the pre-authz behavior during rollout. -To override the backend URL (e.g. MFEs using `@edx/frontend-platform`), pass `apiBaseUrl` -in the options argument: +To override the backend URL (e.g. when the authz service runs on a different backend such as +Studio), pass `apiBaseUrl` in the options argument: ```typescript -import { usePermissions } from '@openedx/frontend-base'; -import { getConfig } from '@edx/frontend-platform'; +import { usePermissions, getSiteConfig } from '@openedx/frontend-base'; const { enableAuthz } = useWaffleFlags(courseId); const { isLoading, isError, canViewGrading } = usePermissions( { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId } }, enableAuthz ?? false, - { apiBaseUrl: getConfig().LMS_BASE_URL }, + { apiBaseUrl: getSiteConfig().lmsBaseUrl }, ); ``` @@ -102,8 +101,7 @@ Avoid calling `usePermissions` directly in every component. Create a single MFE- wrapper that encapsulates the waffle flag check and base URL: ```typescript -import { usePermissions } from '@openedx/frontend-base'; -import { getConfig } from '@edx/frontend-platform'; +import { usePermissions, getSiteConfig } from '@openedx/frontend-base'; import { useWaffleFlags } from './waffleHooks'; // your MFE's waffle flag hook import type { PermissionValidationQuery } from '@openedx/frontend-base'; @@ -115,7 +113,7 @@ export const useResourcePermissions = ( return usePermissions( permissions, enableAuthz ?? false, - { apiBaseUrl: getConfig().LMS_BASE_URL }, + { apiBaseUrl: getSiteConfig().lmsBaseUrl }, ); }; @@ -149,8 +147,7 @@ const { isLoading, canView, canEdit } = If user roles change mid-session and you need to force a refetch: ```typescript -import { permissionsQueryKeys } from '@openedx/frontend-base'; -import { getConfig } from '@edx/frontend-platform'; +import { permissionsQueryKeys, getSiteConfig } from '@openedx/frontend-base'; // Default — URL comes from getSiteConfig().lmsBaseUrl (set via mergeSiteConfig): queryClient.invalidateQueries({ @@ -159,6 +156,6 @@ queryClient.invalidateQueries({ // Explicit URL — use when you passed apiBaseUrl in UsePermissionsOptions: queryClient.invalidateQueries({ - queryKey: permissionsQueryKeys.validate(myQuery, getConfig().LMS_BASE_URL), + queryKey: permissionsQueryKeys.validate(myQuery, getSiteConfig().lmsBaseUrl), }); ``` diff --git a/runtime/authz/api.ts b/runtime/authz/api.ts index 0f843faf..167af14d 100644 --- a/runtime/authz/api.ts +++ b/runtime/authz/api.ts @@ -12,7 +12,7 @@ export const PERMISSIONS_VALIDATE_PATH = '/api/authz/v1/permissions/validate/me' * Validates whether the currently authenticated user holds the requested permissions * against the openedx-authz backend. * - * @param apiBaseUrl - Base URL of the backend running openedx-authz (e.g. getConfig().LMS_BASE_URL). + * @param apiBaseUrl - Base URL of the backend running openedx-authz (e.g. getSiteConfig().lmsBaseUrl). * @param query - Key/value map of permission check descriptors. * @returns Map of the same keys to boolean allowed values. * Any key absent from the server response resolves to false. diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index fc92d1d0..7fac0014 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -44,7 +44,7 @@ export interface UsePermissionsOptions { * { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId }, * canEditGrading: { action: 'courses.edit_grading_settings', scope: courseId } }, * enableAuthz ?? false, - * { apiBaseUrl: getConfig().LMS_BASE_URL }, + * { apiBaseUrl: getSiteConfig().lmsBaseUrl }, * ); */ export type UsePermissionsResult = { @@ -80,7 +80,7 @@ export type UsePermissionsResult = { * { canViewGrading: { action: 'courses.view_grading_settings', scope: courseId }, * canEditGrading: { action: 'courses.edit_grading_settings', scope: courseId } }, * enableAuthzCourseAuthoring ?? false, - * { apiBaseUrl: getConfig().LMS_BASE_URL }, + * { apiBaseUrl: getSiteConfig().lmsBaseUrl }, * ); */ export const usePermissions = ( From 3c4a85cd03eb033f223f6e95ec34420fc42907cb Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 28 Aug 2026 10:47:36 +1000 Subject: [PATCH 07/11] docs: update hoew to --- docs/how_tos/permissions.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index 80184eb4..42b4ac5d 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -8,7 +8,10 @@ to the backend. ## Prerequisites -Ensure your app root is wrapped with a `QueryClientProvider` from `@tanstack/react-query`. +Permission requests are managed with TanStack Query, so a `QueryClientProvider` must be +present above the components calling these hooks. `frontend-base` already provides one in its +shell, so apps running inside it need no setup. Outside `frontend-base` you have to wrap your +app root with a `QueryClientProvider` yourself. --- @@ -135,8 +138,6 @@ const { isLoading, canView, canEdit } = inline strings — prevents typos and makes global renames easy. - **Use query builder helpers** (`getGradingPermissions(courseId)`) to build the query object — keeps permission definitions co-located with the feature they belong to. -- **Do not duplicate `{ action, scope }` pairs** within a single query — only the first - matching key is mapped in the response. - **Keep `featureEnabled` close to the flag source** — the boolean should come directly from your waffle flag check, not be stored in state or passed through many layers. From 2e09fe5f139dbe1be84e0256ef991b7c1c832581 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 28 Aug 2026 11:27:32 +1000 Subject: [PATCH 08/11] test: improve hooks test suite --- runtime/authz/hooks.test.tsx | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/runtime/authz/hooks.test.tsx b/runtime/authz/hooks.test.tsx index 7a4f4b7d..62f53741 100644 --- a/runtime/authz/hooks.test.tsx +++ b/runtime/authz/hooks.test.tsx @@ -2,6 +2,8 @@ import React from 'react'; import { renderHook, waitFor } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { getAuthenticatedHttpClient } from '../auth'; +import { getSiteConfig } from '../config'; +import { PERMISSIONS_VALIDATE_PATH } from './api'; import { usePermissions, permissionsQueryKeys } from './hooks'; jest.mock('../auth', () => ({ @@ -18,13 +20,15 @@ const createWrapper = () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); - return ({ children }: { children: React.ReactNode }) => ( - {children} - ); + function Wrapper({ children }: { children: React.ReactNode }) { + return {children}; + } + return Wrapper; }; describe('usePermissions', () => { beforeEach(() => jest.clearAllMocks()); + afterEach(() => jest.restoreAllMocks()); it('returns actual server values when featureEnabled is true', async () => { (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ @@ -129,7 +133,29 @@ describe('usePermissions', () => { expect(result.current.isError).toBe(true); expect(result.current.canView).toBe(false); expect(result.current.canEdit).toBe(false); - jest.restoreAllMocks(); + }); + + it('defaults apiBaseUrl to getSiteConfig().lmsBaseUrl when the option is omitted', async () => { + const postMock = jest.fn().mockResolvedValue({ + data: [ + { action: 'courses.view_grading_settings', scope: 'course-v1:org+course+run', allowed: true }, + { action: 'courses.edit_grading_settings', scope: 'course-v1:org+course+run', allowed: false }, + ], + }); + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ post: postMock }); + + const { result } = renderHook( + () => usePermissions(QUERY, true), + { wrapper: createWrapper() }, + ); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect(postMock).toHaveBeenCalledWith( + `${getSiteConfig().lmsBaseUrl}${PERMISSIONS_VALIDATE_PATH}`, + Object.values(QUERY), + ); + expect(result.current.canView).toBe(true); + expect(result.current.canEdit).toBe(false); }); it('scopes cache by apiBaseUrl — different base URLs produce distinct query keys', () => { From f81d2cbc9db584477fa3c16506f93c129905aa77 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 28 Aug 2026 14:51:42 +1000 Subject: [PATCH 09/11] refactor: take in cosideration featureEnabled when loading and improve test --- docs/how_tos/permissions.md | 12 ++++++------ runtime/authz/hooks.test.tsx | 25 +++++++++++++++++++++++++ runtime/authz/hooks.ts | 11 ++++++++--- runtime/authz/index.ts | 1 + 4 files changed, 40 insertions(+), 9 deletions(-) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index 42b4ac5d..719e74f1 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -30,7 +30,7 @@ reference in the openedx-authz documentation. ```typescript import type { PermissionValidationQuery } from '@openedx/frontend-base'; -const query: PermissionValidationQuery = { +const query = { canViewGrading: { action: 'courses.view_grading_settings', scope: 'course-v1:org+course+run', @@ -39,7 +39,7 @@ const query: PermissionValidationQuery = { action: 'courses.edit_grading_settings', scope: 'course-v1:org+course+run', }, -}; +} satisfies PermissionValidationQuery; ``` ### Caching @@ -61,7 +61,7 @@ Permission keys are spread at the top level — no nested `.permissions` object. import { usePermissions } from '@openedx/frontend-base'; // featureEnabled is required — always pass the resolved waffle flag boolean: -const { enableAuthz } = useWaffleFlags(resourceId); +const { enableAuthz, isLoading: isLoadingFlag } = useWaffleFlags(resourceId); const { isLoading, isError, isAuthzEnabled, canViewGrading, canEditGrading } = usePermissions( { canViewGrading: { action: 'courses.view_grading_settings', scope: resourceId }, @@ -70,7 +70,7 @@ const { isLoading, isError, isAuthzEnabled, canViewGrading, canEditGrading } = u enableAuthz ?? false, ); -if (isLoading) { return ; } +if (isLoadingFlag || isLoading) { return ; } if (isError) { return ; } if (!canViewGrading) { return ; } ``` @@ -120,10 +120,10 @@ export const useResourcePermissions = ( ); }; -export const getResourcePermissions = (resourceId: string): PermissionValidationQuery => ({ +export const getResourcePermissions = (resourceId: string) => ({ canView: { action: 'resources.view', scope: resourceId }, canEdit: { action: 'resources.edit', scope: resourceId }, -}); +} satisfies PermissionValidationQuery); // Usage in any component: const { isLoading, canView, canEdit } = diff --git a/runtime/authz/hooks.test.tsx b/runtime/authz/hooks.test.tsx index 62f53741..70a711af 100644 --- a/runtime/authz/hooks.test.tsx +++ b/runtime/authz/hooks.test.tsx @@ -158,6 +158,31 @@ describe('usePermissions', () => { expect(result.current.canEdit).toBe(false); }); + it('keeps a flag-off consumer at all-true while a flag-on consumer fetches the same cache key', () => { + (getAuthenticatedHttpClient as jest.Mock).mockReturnValue({ + post: jest.fn(() => new Promise(() => {})), // never resolves + }); + + // Both hooks share one QueryClient, so they observe the same query entry. + const { result } = renderHook( + () => ({ + enabled: usePermissions(QUERY, true, { apiBaseUrl: BASE_URL }), + disabled: usePermissions(QUERY, false, { apiBaseUrl: BASE_URL }), + }), + { wrapper: createWrapper() }, + ); + + // The flag-on consumer is legitimately in flight. + expect(result.current.enabled.isLoading).toBe(true); + expect(result.current.enabled.canView).toBeUndefined(); + + // The flag-off consumer must keep pre-authz behavior regardless of the shared fetch. + expect(result.current.disabled.isAuthzEnabled).toBe(false); + expect(result.current.disabled.isLoading).toBe(false); + expect(result.current.disabled.canView).toBe(true); + expect(result.current.disabled.canEdit).toBe(true); + }); + it('scopes cache by apiBaseUrl — different base URLs produce distinct query keys', () => { const keyA = permissionsQueryKeys.validate(QUERY, 'http://lms-a.example.com'); const keyB = permissionsQueryKeys.validate(QUERY, 'http://lms-b.example.com'); diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index 7fac0014..6f351dd4 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -102,7 +102,12 @@ export const usePermissions = ( staleTime, }); - const permissionResults = isLoading + // Derived once: a disabled consumer must never be treated as loading, even when it + // shares a cache key with an enabled consumer whose fetch is in flight. Blanking the + // keys off the raw isLoading there would return isLoading: false with undefined keys. + const isPermissionsLoading = featureEnabled && isLoading; + + const permissionResults = isPermissionsLoading ? ({} as PermissionValidationAnswer) : (Object.keys(query) as (keyof Query)[]).reduce( (acc, key) => { @@ -113,8 +118,8 @@ export const usePermissions = ( ); return { - isLoading: featureEnabled ? isLoading : false, - isError: featureEnabled ? isError : false, + isLoading: isPermissionsLoading, + isError: featureEnabled && isError, isAuthzEnabled: featureEnabled, ...permissionResults, } as UsePermissionsResult; diff --git a/runtime/authz/index.ts b/runtime/authz/index.ts index f31dfd21..89d4d068 100644 --- a/runtime/authz/index.ts +++ b/runtime/authz/index.ts @@ -1,3 +1,4 @@ +export { validatePermissions } from './api'; export { usePermissions, permissionsQueryKeys } from './hooks'; export type { UsePermissionsOptions, UsePermissionsResult } from './hooks'; export type { PermissionValidationQuery, PermissionValidationAnswer } from './types'; From f6971bce910d1ce5a6b16f9e92bfec652bcd013d Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 28 Aug 2026 13:45:46 +1000 Subject: [PATCH 10/11] docs: add a section to explain when to use validatePermissions --- docs/how_tos/permissions.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/how_tos/permissions.md b/docs/how_tos/permissions.md index 719e74f1..22c0acb9 100644 --- a/docs/how_tos/permissions.md +++ b/docs/how_tos/permissions.md @@ -160,3 +160,25 @@ queryClient.invalidateQueries({ queryKey: permissionsQueryKeys.validate(myQuery, getSiteConfig().lmsBaseUrl), }); ``` + +--- + +## `validatePermissions` (outside React) + +`validatePermissions` is the raw service call that `usePermissions` wraps. Prefer the hook in +components: it adds the `featureEnabled` gate and the shared cache, and the raw call provides +neither. Reach for `validatePermissions` only where hooks cannot run, e.g. a route loader, +a prefetch, or an imperative check outside the render tree. + +```typescript +import { validatePermissions, getSiteConfig } from '@openedx/frontend-base'; + +const answer = await validatePermissions(getSiteConfig().lmsBaseUrl, { + canViewGrading: { action: 'courses.view_grading_settings', scope: courseId }, +}); +// -> { canViewGrading: true } +``` + +Keys absent from the server response resolve to `false`. Note that this call always hits the +backend — it has no `featureEnabled` parameter, so gating on your waffle flag is your +responsibility. \ No newline at end of file From 47da6df7aac868802e6627379ab32dc71b089dc6 Mon Sep 17 00:00:00 2001 From: Diana Olarte Date: Fri, 28 Aug 2026 13:53:57 +1000 Subject: [PATCH 11/11] style: fix linter after rebase --- runtime/authz/hooks.ts | 12 ++++++------ runtime/authz/types.ts | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/runtime/authz/hooks.ts b/runtime/authz/hooks.ts index 6f351dd4..2878207c 100644 --- a/runtime/authz/hooks.ts +++ b/runtime/authz/hooks.ts @@ -19,19 +19,19 @@ export const permissionsQueryKeys = { export interface UsePermissionsOptions { /** Default false — authz returns definitive answers; retrying 403s wastes requests. */ - retry?: boolean | number, + retry?: boolean | number; /** * Base URL of the backend running openedx-authz. * Defaults to getSiteConfig().lmsBaseUrl when omitted. * Pass explicitly when the authz service requires a different backend (e.g. Studio). */ - apiBaseUrl?: string, + apiBaseUrl?: string; /** * How long (in ms) the cached result is considered fresh before TanStack Query refetches. * Defaults to 5 minutes. Use permissionsQueryKeys to invalidate manually when user roles * change mid-session. */ - staleTime?: number, + staleTime?: number; } /** @@ -48,9 +48,9 @@ export interface UsePermissionsOptions { * ); */ export type UsePermissionsResult = { - isLoading: boolean, - isError: boolean, - isAuthzEnabled: boolean, + isLoading: boolean; + isError: boolean; + isAuthzEnabled: boolean; } & { [K in keyof Query]: boolean | undefined }; /** diff --git a/runtime/authz/types.ts b/runtime/authz/types.ts index cd9d6cfa..4ffc4c93 100644 --- a/runtime/authz/types.ts +++ b/runtime/authz/types.ts @@ -1,10 +1,10 @@ export interface PermissionValidationRequestItem { - action: string, - scope?: string, + action: string; + scope?: string; } export interface PermissionValidationResponseItem extends PermissionValidationRequestItem { - allowed: boolean, + allowed: boolean; } export type PermissionValidationQuery = Record;