-
Notifications
You must be signed in to change notification settings - Fork 171
feat: Implement querying openedx-authz for publish permissions #2685
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bradenmacdonald
merged 13 commits into
openedx:master
from
WGU-Open-edX:rod/authz-publish-permissions
Dec 4, 2025
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
f57976e
feat: Implement querying openedx-authz for publish permissions
rodmgwgu feb5cee
squash!: Fix lint issues, correct appId
rodmgwgu 5f64fb3
squash!: Fixing permissions
rodmgwgu d7b1a3c
squash!: Fix existing tests
rodmgwgu e5f10d2
squash!: Fix lint issues
rodmgwgu 03a8d7d
squash!: Improve way of mocking validateUserPermissions, remove unnee…
rodmgwgu b21a520
squash!: lint fix
rodmgwgu 35d53ab
squash!: Add test for authz hook
rodmgwgu f7c566f
squash!: Attend PR comments
rodmgwgu 129e771
squash!: use authz instead of appId for useValidateUserPermissions query
rodmgwgu a435e1d
squash!: Improve permission validation hook with a clearer and safer API
rodmgwgu 546eccf
squash!: Fix tests
rodmgwgu 6d8852c
squash!: Use realistic examples on tests and docs
rodmgwgu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| export const CONTENT_LIBRARY_PERMISSIONS = { | ||
| DELETE_LIBRARY: 'content_libraries.delete_library', | ||
| MANAGE_LIBRARY_TAGS: 'content_libraries.manage_library_tags', | ||
| VIEW_LIBRARY: 'content_libraries.view_library', | ||
|
|
||
| EDIT_LIBRARY_CONTENT: 'content_libraries.edit_library_content', | ||
| PUBLISH_LIBRARY_CONTENT: 'content_libraries.publish_library_content', | ||
| REUSE_LIBRARY_CONTENT: 'content_libraries.reuse_library_content', | ||
|
|
||
| CREATE_LIBRARY_COLLECTION: 'content_libraries.create_library_collection', | ||
| EDIT_LIBRARY_COLLECTION: 'content_libraries.edit_library_collection', | ||
| DELETE_LIBRARY_COLLECTION: 'content_libraries.delete_library_collection', | ||
|
|
||
| MANAGE_LIBRARY_TEAM: 'content_libraries.manage_library_team', | ||
| VIEW_LIBRARY_TEAM: 'content_libraries.view_library_team', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth'; | ||
| import { | ||
| PermissionValidationAnswer, | ||
| PermissionValidationQuery, | ||
| PermissionValidationRequestItem, | ||
| PermissionValidationResponseItem, | ||
| } from '@src/authz/types'; | ||
| import { getApiUrl } from './utils'; | ||
|
|
||
| export const validateUserPermissions = async ( | ||
| query: PermissionValidationQuery, | ||
| ): Promise<PermissionValidationAnswer> => { | ||
| // Convert the validations query object into an array for the API request | ||
| const request: PermissionValidationRequestItem[] = Object.values(query); | ||
|
|
||
| const { data }: { data: PermissionValidationResponseItem[] } = await getAuthenticatedHttpClient().post( | ||
| getApiUrl('/api/authz/v1/permissions/validate/me'), | ||
| request, | ||
| ); | ||
|
|
||
| // Convert the API response back into the expected answer format | ||
| const result: PermissionValidationAnswer = {}; | ||
| data.forEach((item: { action: string; scope?: string; allowed: boolean }) => { | ||
| const key = Object.keys(query).find( | ||
| (k) => query[k].action === item.action | ||
| && query[k].scope === item.scope, | ||
| ); | ||
| if (key) { | ||
| result[key] = item.allowed; | ||
| } | ||
| }); | ||
|
|
||
| // Fill any missing keys with false | ||
| Object.keys(query).forEach((key) => { | ||
| if (!(key in result)) { | ||
| result[key] = false; | ||
| } | ||
| }); | ||
|
|
||
| return result; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| import { act, ReactNode } from 'react'; | ||
| import { renderHook, waitFor } from '@testing-library/react'; | ||
| import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; | ||
| import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth'; | ||
| import { useUserPermissions } from './apiHooks'; | ||
|
|
||
| jest.mock('@edx/frontend-platform/auth', () => ({ | ||
| getAuthenticatedHttpClient: jest.fn(), | ||
| })); | ||
|
|
||
| const createWrapper = () => { | ||
| const queryClient = new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { | ||
| retry: false, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const wrapper = ({ children }: { children: ReactNode }) => ( | ||
| <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> | ||
| ); | ||
|
|
||
| return wrapper; | ||
| }; | ||
|
|
||
| const singlePermission = { | ||
| canRead: { | ||
| action: 'example.read', | ||
| scope: 'lib:example-org:test-lib', | ||
| }, | ||
| }; | ||
|
|
||
| const mockValidSinglePermission = [ | ||
| { action: 'example.read', scope: 'lib:example-org:test-lib', allowed: true }, | ||
| ]; | ||
|
|
||
| const mockInvalidSinglePermission = [ | ||
| { action: 'example.read', scope: 'lib:example-org:test-lib', allowed: false }, | ||
| ]; | ||
|
|
||
| const mockEmptyPermissions = [ | ||
| // No permissions returned | ||
| ]; | ||
|
|
||
| const multiplePermissions = { | ||
| canRead: { | ||
| action: 'example.read', | ||
| scope: 'lib:example-org:test-lib', | ||
| }, | ||
| canWrite: { | ||
| action: 'example.write', | ||
| scope: 'lib:example-org:test-lib', | ||
| }, | ||
| }; | ||
|
|
||
| const mockValidMultiplePermissions = [ | ||
| { action: 'example.read', scope: 'lib:example-org:test-lib', allowed: true }, | ||
| { action: 'example.write', scope: 'lib:example-org:test-lib', allowed: true }, | ||
| ]; | ||
|
|
||
| const mockInvalidMultiplePermissions = [ | ||
| { action: 'example.read', scope: 'lib:example-org:test-lib', allowed: false }, | ||
| { action: 'example.write', scope: 'lib:example-org:test-lib', allowed: false }, | ||
| ]; | ||
|
|
||
| describe('useUserPermissions', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('returns allowed true when permission is valid', async () => { | ||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockResolvedValueOnce({ data: mockValidSinglePermission }), | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useUserPermissions(singlePermission), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
|
|
||
| await waitFor(() => expect(result.current).toBeDefined()); | ||
| await waitFor(() => expect(result.current.data).toBeDefined()); | ||
|
|
||
| expect(getAuthenticatedHttpClient).toHaveBeenCalled(); | ||
| expect(result.current.data!.canRead).toBe(true); | ||
| }); | ||
|
|
||
| it('returns allowed false when permission is invalid', async () => { | ||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockResolvedValue({ data: mockInvalidSinglePermission }), | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useUserPermissions(singlePermission), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
| await waitFor(() => expect(result.current).toBeDefined()); | ||
| await waitFor(() => expect(result.current.data).toBeDefined()); | ||
|
|
||
| expect(getAuthenticatedHttpClient).toHaveBeenCalled(); | ||
| expect(result.current.data!.canRead).toBe(false); | ||
| }); | ||
|
|
||
| it('returns allowed true when multiple permissions are valid', async () => { | ||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockResolvedValueOnce({ data: mockValidMultiplePermissions }), | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useUserPermissions(multiplePermissions), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
|
|
||
| await waitFor(() => expect(result.current).toBeDefined()); | ||
| await waitFor(() => expect(result.current.data).toBeDefined()); | ||
|
|
||
| expect(getAuthenticatedHttpClient).toHaveBeenCalled(); | ||
| expect(result.current.data!.canRead).toBe(true); | ||
| expect(result.current.data!.canWrite).toBe(true); | ||
| }); | ||
|
|
||
| it('returns allowed false when multiple permissions are invalid', async () => { | ||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockResolvedValue({ data: mockInvalidMultiplePermissions }), | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useUserPermissions(multiplePermissions), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
| await waitFor(() => expect(result.current).toBeDefined()); | ||
| await waitFor(() => expect(result.current.data).toBeDefined()); | ||
|
|
||
| expect(getAuthenticatedHttpClient).toHaveBeenCalled(); | ||
| expect(result.current.data!.canRead).toBe(false); | ||
| expect(result.current.data!.canWrite).toBe(false); | ||
| }); | ||
|
|
||
| it('returns allowed false when the permission is not included in the server response', async () => { | ||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockResolvedValue({ data: mockEmptyPermissions }), | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useUserPermissions(singlePermission), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
| await waitFor(() => expect(result.current).toBeDefined()); | ||
| await waitFor(() => expect(result.current.data).toBeDefined()); | ||
|
|
||
| expect(getAuthenticatedHttpClient).toHaveBeenCalled(); | ||
| expect(result.current.data!.canRead).toBe(false); | ||
| }); | ||
|
|
||
| it('handles error when the API call fails', async () => { | ||
| const mockError = new Error('API Error'); | ||
|
|
||
| getAuthenticatedHttpClient.mockReturnValue({ | ||
| post: jest.fn().mockRejectedValue(new Error('API Error')), | ||
| }); | ||
|
|
||
| try { | ||
| act(() => { | ||
| renderHook(() => useUserPermissions(singlePermission), { | ||
| wrapper: createWrapper(), | ||
| }); | ||
| }); | ||
| } catch (error) { | ||
| expect(error).toEqual(mockError); // Check for the expected error | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { useQuery } from '@tanstack/react-query'; | ||
| import { PermissionValidationAnswer, PermissionValidationQuery } from '@src/authz/types'; | ||
| import { validateUserPermissions } from './api'; | ||
|
|
||
| const adminConsoleQueryKeys = { | ||
| all: ['authz'], | ||
| permissions: (permissions: PermissionValidationQuery) => [...adminConsoleQueryKeys.all, 'validatePermissions', permissions] as const, | ||
| }; | ||
|
|
||
| /** | ||
| * React Query hook to validate if the current user has permissions over a certain object in the instance. | ||
| * It helps to: | ||
| * - Determine whether the current user can access certain object. | ||
| * - Provide role-based rendering logic for UI components. | ||
| * | ||
| * @param permissions - A key/value map of objects and actions to validate. | ||
| * The key is an arbitrary string to identify the permission check, | ||
| * and the value is an object containing the action and optional scope. | ||
| * | ||
| * @example | ||
| * const { isLoading, data } = useUserPermissions({ | ||
| * canRead: { | ||
| * action: "content_libraries.view_library", | ||
| * scope: "lib:OpenedX:CSPROB" | ||
| * } | ||
| * }); | ||
| * if (data.canRead) { ... } | ||
| * | ||
| */ | ||
| export const useUserPermissions = ( | ||
| permissions: PermissionValidationQuery, | ||
| ) => useQuery<PermissionValidationAnswer, Error>({ | ||
| queryKey: adminConsoleQueryKeys.permissions(permissions), | ||
| queryFn: () => validateUserPermissions(permissions), | ||
| retry: false, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| import { getConfig } from '@edx/frontend-platform'; | ||
|
|
||
| export const getApiUrl = (path: string) => `${getConfig().LMS_BASE_URL}${path || ''}`; | ||
| export const getStudioApiUrl = (path: string) => `${getConfig().STUDIO_BASE_URL}${path || ''}`; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| export interface PermissionValidationRequestItem { | ||
| action: string; | ||
| scope?: string; | ||
| } | ||
|
|
||
| export interface PermissionValidationResponseItem extends PermissionValidationRequestItem { | ||
| allowed: boolean; | ||
| } | ||
|
|
||
| export interface PermissionValidationQuery { | ||
| [permissionKey: string]: PermissionValidationRequestItem; | ||
| } | ||
|
|
||
| export interface PermissionValidationAnswer { | ||
| [permissionKey: string]: boolean; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.