Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ Added
* ``assign_role_to_subject_in_scope`` now raises ``CustomRoleNotFoundError`` for a custom role that
does not exist or was removed. It assigns custom roles under the same lock as removing them, so
an assignment cannot outlive a concurrent removal. Static role assignments are unchanged.
* Added ``scope_display_name`` and ``org_display_name`` to each result of the
``/api/authz/v1/assignments/`` endpoint. Unresolvable scopes and orgs, such as glob scopes or
deleted resources, return an empty string.
* Added authorization schema version ``1.1``, with its own ``authz-schema-v1.1.json``. It adds an
optional ``depends_on`` list to permissions (ADR 0034). Files of versions ``1.0`` and ``1.1`` can
be loaded together. Validation rejects unknown dependencies, dependency cycles, dependencies that
Expand Down
24 changes: 24 additions & 0 deletions src/openedx_authz/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

from django.contrib.auth import get_user_model
from django.db.models import Q
from organizations.models import Organization

from openedx_authz.api.data import (
GLOBAL_SCOPE_WILDCARD,
ContentLibraryData,
CourseOverviewData,
RoleAssignmentData,
Expand Down Expand Up @@ -119,3 +121,25 @@ def get_scope_display_name_map(scope_external_keys: set[str]) -> dict[str, str]:
log.exception("Failed to fetch CourseOverview display names")

return display_name_map


def get_org_display_name_map(org_short_names: set[str]) -> dict[str, str]:
"""Build a mapping of organization short names to their display names.

Uses a single query so callers can resolve the orgs of many assignments at
once. Inactive organizations are included because existing assignments on
them still need a readable name.

Args:
org_short_names: The organization short names to resolve. The global
wildcard is ignored because it does not match a single organization.

Returns:
A dict mapping each found short name to its display name. Short names
without a matching organization are omitted.
"""
short_names = org_short_names - {GLOBAL_SCOPE_WILDCARD}
if not short_names:
return {}
orgs = Organization.objects.filter(short_name__in=short_names).values_list("short_name", "name")
return dict(orgs)
3 changes: 2 additions & 1 deletion src/openedx_authz/rest_api/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,11 @@ class ScopesTypeField(BaseEnum):


class SerializedAssignment(TypedDict, total=False):
"""Shape of an inline assignment as produced by ``TeamMemberAssignmentInlineSerializer``."""
"""Shape of a serialized assignment as produced by the team member assignment serializers."""

role: str
org: str
org_display_name: str
scope: str
scope_display_name: str
permission_count: int
21 changes: 20 additions & 1 deletion src/openedx_authz/rest_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
GLOBAL_SCOPE_WILDCARD,
ScopeData,
)
from openedx_authz.api.utils import get_scope_display_name_map
from openedx_authz.api.utils import get_org_display_name_map, get_scope_display_name_map
from openedx_authz.rest_api.data import (
AssignmentSortField,
BaseEnum,
Expand Down Expand Up @@ -300,3 +300,22 @@ def inject_scope_display_names(assignments: list[SerializedAssignment]) -> None:
display_name_map = get_scope_display_name_map(scope_keys)
for assignment in assignments:
assignment["scope_display_name"] = display_name_map.get(assignment.get("scope", ""), "")


def inject_org_display_names(assignments: list[SerializedAssignment]) -> None:
"""Set ``org_display_name`` in-place on serialized assignments using one bulk lookup.

Callers must pass only the assignments of the current page, after filtering,
sorting and pagination, so the lookup cost does not grow with the total
number of assignments. Unresolvable orgs (the global wildcard or orgs with
no matching organization) get an empty string.

Args:
assignments: Serialized assignments for the current page. Each one
must have an ``org`` key. They are modified in-place, and
``org_display_name`` is set on every entry.
"""
org_short_names = {a["org"] for a in assignments if a.get("org")}
display_name_map = get_org_display_name_map(org_short_names)
for assignment in assignments:
assignment["org_display_name"] = display_name_map.get(assignment.get("org", ""), "")
10 changes: 10 additions & 0 deletions src/openedx_authz/rest_api/v1/admin_console/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,20 @@ def to_representation(self, instance):
class TeamMemberUserAssignmentSerializer(TeamMemberAssignmentSerializer): # pylint: disable=abstract-method
"""Serializer for team member assignments with user information."""

scope_display_name = serializers.SerializerMethodField()
org_display_name = serializers.SerializerMethodField()
full_name = serializers.SerializerMethodField()
username = serializers.SerializerMethodField()
email = serializers.SerializerMethodField()

def get_scope_display_name(self, _obj: api.UserAssignmentData | api.SuperAdminAssignmentData) -> str:
"""Return an empty placeholder; the view injects the real value post-pagination."""
return ""

def get_org_display_name(self, _obj: api.UserAssignmentData | api.SuperAdminAssignmentData) -> str:
"""Return an empty placeholder; the view injects the real value post-pagination."""
return ""

def get_full_name(self, obj: api.UserAssignmentData | api.SuperAdminAssignmentData) -> str:
"""Get the full name from the UserProfile."""
user = obj.user
Expand Down
10 changes: 8 additions & 2 deletions src/openedx_authz/rest_api/v1/admin_console/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
from openedx_authz.models.scopes import get_content_library_model, get_course_overview_model
from openedx_authz.rest_api.data import ScopesQuerySetFields, ScopesTypeField
from openedx_authz.rest_api.decorators import authz_permissions, view_auth_classes
from openedx_authz.rest_api.utils import inject_scope_display_names
from openedx_authz.rest_api.utils import inject_org_display_names, inject_scope_display_names
from openedx_authz.rest_api.v1.admin_console.filters import (
TeamMemberAssignmentsOrderingFilter,
TeamMemberOrderingFilter,
Expand Down Expand Up @@ -824,7 +824,9 @@ class AssignmentsAPIView(APIView):
- is_superadmin: whether this entry denotes a superadmin
- role: The role
- org: The org over which this role is applied
- org_display_name: The display name of the org, or an empty string if it cannot be resolved
- scope: The scope over which this role is applied
- scope_display_name: The display name of the scope, or an empty string if it cannot be resolved
- permission_count: The number of permissions that apply to this role
- full_name: The full name of the user in this assignment
- username: The username of the user in this assignment
Expand Down Expand Up @@ -852,6 +854,8 @@ class AssignmentsAPIView(APIView):
"org": "OpenedX",
"scope": "course-v1:OpenedX+DemoX+DemoCourse",
"permission_count": 27,
"scope_display_name": "Demonstration Course",
"org_display_name": "Open edX",
"full_name": "",
"username": "contributor",
"email": "contributor@example.com"
Expand Down Expand Up @@ -922,7 +926,9 @@ def get(self, request: HttpRequest) -> Response:
for backend in self.filter_backends:
assignments = backend().filter_queryset(request, assignments, self)

# Paginate
# Paginate, then resolve display names in bulk for the current page only.
paginator = self.pagination_class()
paginated_response_data = paginator.paginate_queryset(assignments, request)
inject_scope_display_names(paginated_response_data)
inject_org_display_names(paginated_response_data)
return paginator.get_paginated_response(paginated_response_data)
47 changes: 47 additions & 0 deletions src/openedx_authz/tests/api/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Unit tests for openedx_authz.api.utils."""

from django.test import TestCase
from organizations.models import Organization

from openedx_authz.api.data import GLOBAL_SCOPE_WILDCARD
from openedx_authz.api.utils import get_org_display_name_map


class TestGetOrgDisplayNameMap(TestCase):
"""Tests for resolving organization short names to display names."""

@classmethod
def setUpTestData(cls):
"""Create active and inactive organizations whose names differ from their short names."""
Organization.objects.create(short_name="AlphaU", name="Alpha University")
Organization.objects.create(short_name="BetaI", name="Beta Institute")
Organization.objects.create(short_name="OldOrg", name="Retired Organization", active=False)

def test_resolves_names_in_a_single_query(self):
"""All requested organizations are resolved with one query."""
with self.assertNumQueries(1):
result = get_org_display_name_map({"AlphaU", "BetaI"})

self.assertEqual(result, {"AlphaU": "Alpha University", "BetaI": "Beta Institute"})

def test_includes_inactive_organizations(self):
"""Inactive organizations still resolve, since existing assignments may point to them."""
self.assertEqual(get_org_display_name_map({"OldOrg"}), {"OldOrg": "Retired Organization"})

def test_omits_unknown_organizations(self):
"""Short names without a matching organization are left out of the result."""
self.assertEqual(get_org_display_name_map({"AlphaU", "Missing"}), {"AlphaU": "Alpha University"})

def test_wildcard_only_skips_the_query(self):
"""The global wildcard is not an organization, so no query runs for it."""
with self.assertNumQueries(0):
result = get_org_display_name_map({GLOBAL_SCOPE_WILDCARD})

self.assertEqual(result, {})

def test_empty_input_skips_the_query(self):
"""An empty set returns an empty map without querying."""
with self.assertNumQueries(0):
result = get_org_display_name_map(set())

self.assertEqual(result, {})
98 changes: 95 additions & 3 deletions src/openedx_authz/tests/rest_api/admin_console/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2144,7 +2144,8 @@ class TestAssignmentsAPIView(ViewTestMixin):
regular_7 (library_contributor), regular_8 (library_user)

URL: /api/authz/v1/assignments/
Response fields per item: is_superadmin, role, org, scope, permission_count, full_name, username, email
Response fields per item: is_superadmin, role, org, org_display_name, scope, scope_display_name,
permission_count, full_name, username, email

This endpoint returns one row per (user, assignment) pair — i.e. assignments are
"unpacked" so each row carries user info alongside the assignment fields.
Expand Down Expand Up @@ -2475,8 +2476,8 @@ def test_response_shape(self):

Expected result:
- Returns 200 OK.
- Each item has is_superadmin, role, org, scope, permission_count,
full_name, username, and email.
- Each item has is_superadmin, role, org, org_display_name, scope,
scope_display_name, permission_count, full_name, username, and email.
"""
response = self.client.get(self.url)

Expand All @@ -2485,7 +2486,9 @@ def test_response_shape(self):
"is_superadmin",
"role",
"org",
"org_display_name",
"scope",
"scope_display_name",
"permission_count",
"full_name",
"username",
Expand Down Expand Up @@ -2675,6 +2678,95 @@ def test_inactive_users_excluded_from_results(self):
inactive_user.is_active = True
inactive_user.save()

def _create_named_org1(self) -> Organization:
"""Give Org1 a display name that differs from its short name.

This keeps the display-name tests from passing by echoing the ``org`` value back.

Returns:
The Org1 organization.
"""
org, _ = Organization.objects.update_or_create(short_name="Org1", defaults={"name": "Organization One"})
return org

def _get_items_for_scope(self, scope: str) -> list[dict]:
"""Return the response items for the given scope, requesting it explicitly.

Args:
scope: The scope external key to filter by.

Returns:
The serialized assignments for that scope.
"""
response = self.client.get(self.url, {"scopes": scope, "page_size": 100})
self.assertEqual(response.status_code, status.HTTP_200_OK)
items = response.data["results"]
self.assertGreater(len(items), 0, f"Expected at least one assignment in {scope}")
return items

def test_display_names_resolved_for_libraries(self):
"""Library assignments get the learning package title and the organization name."""
lib_scope = "lib:Org1:LIB1"
learning_package = LearningPackage.objects.create(title="Intro to CS Library")
ContentLibrary.objects.update_or_create(
slug="LIB1",
org=self._create_named_org1(),
defaults={"locator": lib_scope, "title": "Library model title", "learning_package": learning_package},
)

for item in self._get_items_for_scope(lib_scope):
self.assertEqual(item["scope_display_name"], "Intro to CS Library")
self.assertEqual(item["org_display_name"], "Organization One")

def test_display_names_resolved_for_courses(self):
"""Course assignments get the course overview display name and the organization name."""
self._create_named_org1()
CourseOverview.objects.update_or_create(
id=COURSE_SCOPE_ORG1, defaults={"org": "Org1", "display_name": "Introduction to Computer Science"}
)
assign_role_to_user_in_scope("regular_1", COURSE_STAFF.external_key, COURSE_SCOPE_ORG1)

for item in self._get_items_for_scope(COURSE_SCOPE_ORG1):
self.assertEqual(item["scope_display_name"], "Introduction to Computer Science")
self.assertEqual(item["org_display_name"], "Organization One")

def test_display_names_resolved_for_inactive_org(self):
"""Assignments on an inactive organization still show its name."""
org = self._create_named_org1()
org.active = False
org.save()

for item in self._get_items_for_scope("lib:Org1:LIB1"):
self.assertEqual(item["org_display_name"], "Organization One")

def test_display_names_empty_for_missing_resources(self):
"""A scope with no backing library or organization gets empty display names."""
orphan_scope = "lib:GoneOrg:GONE_LIB"
assign_role_to_user_in_scope("regular_1", LIBRARY_USER.external_key, orphan_scope)

for item in self._get_items_for_scope(orphan_scope):
self.assertEqual(item["scope_display_name"], "")
self.assertEqual(item["org_display_name"], "")

def test_display_names_org_glob_resolves_org_name_only(self):
"""An org-level glob has no scope display name but still resolves its organization."""
self._create_named_org1()
assign_role_to_user_in_scope("regular_1", COURSE_ADMIN.external_key, COURSE_ORG1_GLOB)

for item in self._get_items_for_scope(COURSE_ORG1_GLOB):
self.assertEqual(item["org"], "Org1")
self.assertEqual(item["scope_display_name"], "")
self.assertEqual(item["org_display_name"], "Organization One")

def test_display_names_empty_for_platform_glob(self):
"""A platform-level glob matches no single scope or organization, so both names are empty."""
assign_role_to_user_in_scope("regular_1", LIBRARY_ADMIN.external_key, PLATFORM_LIBRARY_GLOB)

for item in self._get_items_for_scope(PLATFORM_LIBRARY_GLOB):
self.assertEqual(item["org"], "*")
self.assertEqual(item["scope_display_name"], "")
self.assertEqual(item["org_display_name"], "")


@ddt
class TestAssignmentsAPIViewPermissions(ViewTestMixin):
Expand Down