Skip to content

Commit d2d0e63

Browse files
MaferMazumariajgrimaldiclaude
authored
feat: add waffle flag states rest api and util (#358)
* feat: add waffle flag states rest api and util * fix: address PR #358 review comments on get_waffle_flag_states - get_waffle_flag_states used a manual Flag query for the global tier instead of enable_authz_course_authoring, and returned flat booleans for org/course overrides instead of the actual affected orgs/courses, split by whether the override forces the flag on or off. - Adds test coverage for get_waffle_flag_states and WaffleFlagStatesAPIView, and an ADR documenting why this endpoint (issue #358) supersedes PR #361's approach of enforcing the flag cascade inside release-blocking endpoints. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix: rollback to use Flag instead of enable_authz_course_authoring, because that needs an argument * fix: quality tests * docs: bumpversion to 1.21.0 * docs: update the adr --------- Co-authored-by: Maria Grimaldi <maria.grimaldi@edunext.co> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent b7e2484 commit d2d0e63

8 files changed

Lines changed: 365 additions & 2 deletions

File tree

CHANGELOG.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ Change Log
1414
Unreleased
1515
**********
1616

17+
1.21.0 - 2026-07-14
18+
*******************
19+
20+
Added
21+
=====
22+
23+
* Introduced a new REST API endpoint and utility functions to fetch course authoring waffle flag states. (#358)
24+
1725
1.20.1 - 2026-07-03
1826
*******************
1927

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
0015: Expose Course-Authoring Waffle Flag State via REST API
2+
##############################################################
3+
4+
Status
5+
******
6+
7+
**Draft**
8+
9+
Context
10+
*******
11+
12+
``authz.enable_course_authoring`` is a three-tier flag (`ADR 0010`_), where a course override wins over an org override, which in turn wins over the platform default.
13+
14+
`Issue #340`_ and `issue #341`_ report that the admin-console MFE keeps showing Authoring-related roles, scopes, and role assignments even when this flag is off, since nothing currently checks it. Both issues ask for a simpler rule than the full cascade. The Authoring UI should show if the flag is on at any level (platform, org, or course), and hide only if it's off at every level. `A review comment on frontend-app-admin-console#176`_ lays out the fuller course/org/platform truth table this problem could ideally follow.
15+
16+
`PR #361`_ attempted to enforce that full truth table directly inside ``PermissionValidationMeView`` and other REST API endpoints, checking the flag per scope on every request. Per `PR #361's own comment thread`_, those endpoints are release-blocking for Verawood, so baking precise per-scope flag logic into them risked correctness and performance on critical paths without enough test coverage across the framework to be confident in time for the release. That approach was reverted, and the team pivoted to `issue #358`_ instead, exposing the flag's raw state through a dedicated endpoint and letting the admin-console MFE apply the simpler #340/#341 rule itself, deferring precise per-scope filtering to a later cycle.
17+
18+
Neither edx-toggles nor edx-platform expose a suitable public API for this client-facing use case. ``/api/toggles/v0/state/`` (`edx_toggles source`_) can expose override data, but it requires Django staff/admin access and exposes flag state broadly (not just ``authz.enable_course_authoring``). ``WaffleFlagOrgOverrideModel.override_value(name, key)`` and its course-level counterpart (`waffle_utils models source`_) each answer for one specific org or course, not "which orgs/courses have an override."
19+
20+
Decision
21+
********
22+
23+
1. Add ``GET /api/authz/v1/waffle-flag-states/``, backed by ``openedx_authz.utils.get_waffle_flag_states()``, returning the flag's global state plus every org and course that currently has an active override, split into 'on' and 'off' lists.
24+
2. The admin-console MFE decides what to show using this response, applying the #340/#341 rule for this release.
25+
3. This supersedes PR #361's approach of enforcing the full cascade inside REST API endpoints themselves, for this release. PR #361's per-scope logic (``is_scope_visible``/``has_visible_scope``) stays documented on that branch for a future cycle.
26+
4. Making the REST API endpoints themselves aware of the flag is still an open problem, and needs to be addressed on its own. Given the release timeline and the risk PR #361 surfaced, the team chose this more straightforward solution for now.
27+
28+
Consequences
29+
************
30+
31+
#. **Release-blocking endpoints stay untouched.** ``PermissionValidationMeView`` and the other endpoints named in PR #361 keep their existing behavior. This endpoint is additive, isolated, low-risk.
32+
#. **One place answers "what's the flag's state right now."** ``get_waffle_flag_states()`` centralizes the lookup, reusing ``enable_authz_course_authoring()`` for the global tier and querying ``WaffleFlagOrgOverrideModel``/``WaffleFlagCourseOverrideModel`` directly for the org/course tiers, since no public API answers "which orgs/courses have an override."
33+
#. **The MFE bears the filtering complexity.** Applying the #340/#341 "any tier on" rule, and any future precise per-course/per-org filtering, is MFE-side logic from here on.
34+
#. **These override queries scan the whole table, unfiltered by any specific org/course.** For instances with many overrides, this is a full-table read on every call. Not a problem at current scale, but worth revisiting if usage grows (see `issue #360`_).
35+
#. **``openedx_authz.utils`` now depends on** ``common.djangoapps.student.roles.enable_authz_course_authoring`` **and** ``openedx.core.djangoapps.waffle_utils.models``, guarded by the same standalone-import pattern already used elsewhere in this repo (``rest_api/utils.py``, ``handlers.py``). This is a temporary, direct edx-platform dependency, tracked as follow-up work under `issue #360`_ (moving the dependency direction so services depend on ``openedx_authz``).
36+
37+
Rejected Alternatives
38+
**********************
39+
40+
**Enforcing the full per-scope truth table inside release-blocking REST API endpoints (PR #361)**
41+
Correctness and performance across the whole framework weren't validated in time for a release-blocking change, per PR #361's own comment thread. The simpler #340/#341 rule doesn't need per-scope precision to ship.
42+
43+
**Relying on** ``/api/toggles/v0/state/``
44+
This edx-toggles endpoint can expose override data, but it requires Django staff/admin access and is not suitable for this use case. It also exposes flag state broadly (not just ``authz.enable_course_authoring``), which is a security risk for this use case.
45+
46+
References
47+
**********
48+
49+
* `ADR 0010`_
50+
* `Issue #340`_
51+
* `Issue #341`_
52+
* `Issue #358`_
53+
* `Issue #360`_
54+
* `PR #361`_
55+
* `PR #361's own comment thread`_
56+
* `A review comment on frontend-app-admin-console#176`_
57+
58+
.. _ADR 0010: 0010-course-authoring-flag.rst
59+
.. _Issue #340: https://github.com/openedx/openedx-authz/issues/340
60+
.. _issue #340: https://github.com/openedx/openedx-authz/issues/340
61+
.. _Issue #341: https://github.com/openedx/openedx-authz/issues/341
62+
.. _issue #341: https://github.com/openedx/openedx-authz/issues/341
63+
.. _Issue #358: https://github.com/openedx/openedx-authz/issues/358
64+
.. _issue #358: https://github.com/openedx/openedx-authz/issues/358
65+
.. _Issue #360: https://github.com/openedx/openedx-authz/issues/360
66+
.. _issue #360: https://github.com/openedx/openedx-authz/issues/360
67+
.. _PR #361: https://github.com/openedx/openedx-authz/pull/361
68+
.. _PR #361's own comment thread: https://github.com/openedx/openedx-authz/pull/361#issuecomment-4967053225
69+
.. _A review comment on frontend-app-admin-console#176: https://github.com/openedx/frontend-app-admin-console/pull/176#issuecomment-4900922914
70+
.. _edx_toggles source: https://github.com/openedx/edx-toggles/blob/master/edx_toggles/toggles/state/internal/report.py
71+
.. _waffle_utils models source: https://github.com/openedx/edx-platform/blob/master/openedx/core/djangoapps/waffle_utils/models.py

openedx_authz/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@
44

55
import os
66

7-
__version__ = "1.20.1"
7+
__version__ = "1.21.0"
88

99
ROOT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))

openedx_authz/rest_api/v1/urls.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@
2020
),
2121
path("assignments/", views.AssignmentsAPIView.as_view(), name="assignment-list"),
2222
path("scopes/", views.ScopesAPIView.as_view(), name="scope-list"),
23+
path("waffle-flag-states/", views.WaffleFlagStatesAPIView.as_view(), name="waffle-flag-states"),
2324
]

openedx_authz/rest_api/v1/views.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
UserValidationAPIViewResponseSerializer,
7878
UserValidationAPIViewSerializer,
7979
)
80-
from openedx_authz.utils import get_user_by_username_or_email
80+
from openedx_authz.utils import get_user_by_username_or_email, get_waffle_flag_states
8181

8282
logger = logging.getLogger(__name__)
8383

@@ -1374,3 +1374,34 @@ def get(self, request: HttpRequest) -> Response:
13741374
paginator = self.pagination_class()
13751375
paginated_response_data = paginator.paginate_queryset(assignments, request)
13761376
return paginator.get_paginated_response(paginated_response_data)
1377+
1378+
1379+
@view_auth_classes()
1380+
class WaffleFlagStatesAPIView(APIView):
1381+
"""
1382+
Simple API view that returns the waffle flag states from utils.get_waffle_flag_states.
1383+
1384+
**Endpoints**
1385+
1386+
- GET: Retrieve the enablement state of the course-authoring waffle flag across different scopes.
1387+
1388+
**Response Format**
1389+
1390+
* 'global' (bool): True if the global waffle flag is enabled.
1391+
* 'org_overrides' (dict): Orgs with an organization-level override, as 'on'
1392+
(forces the flag on) and 'off' (forces the flag off) lists.
1393+
* 'course_overrides' (dict): Courses with a course-level override, split the same way.
1394+
1395+
**Example Request**
1396+
1397+
GET /api/authz/v1/waffle-flag-states/
1398+
"""
1399+
1400+
def get(self, request: HttpRequest) -> Response:
1401+
"""Retrieve the enablement state of the course-authoring waffle flag across different scopes."""
1402+
try:
1403+
data = get_waffle_flag_states()
1404+
return Response(data, status=status.HTTP_200_OK)
1405+
except Exception as e: # pylint: disable=broad-exception-caught
1406+
logger.exception("Error getting waffle flag states: %s", e)
1407+
return Response({"message": "error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

openedx_authz/tests/rest_api/test_views.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4338,3 +4338,54 @@ def test_scope_permission_vs_platform_permission(self, username, scopes, expecte
43384338
response = self._put_lib(scopes, roles.LIBRARY_ADMIN.external_key)
43394339

43404340
self.assertEqual(response.status_code, expected_status)
4341+
4342+
4343+
class TestWaffleFlagStatesAPIView(ViewTestMixin):
4344+
"""Test suite for WaffleFlagStatesAPIView."""
4345+
4346+
def setUp(self):
4347+
"""Set up test fixtures."""
4348+
super().setUp()
4349+
self.url = reverse("openedx_authz:waffle-flag-states")
4350+
4351+
def test_get_returns_the_waffle_flag_states(self):
4352+
"""Test GET /waffle-flag-states/ with a successful lookup.
4353+
4354+
Expected result:
4355+
- Returns 200 OK status.
4356+
- The response body is whatever get_waffle_flag_states returns, unchanged.
4357+
"""
4358+
flag_states = {
4359+
"global": True,
4360+
"org_overrides": {"on": ["Org1"], "off": []},
4361+
"course_overrides": {"on": [], "off": ["course-v1:Org1+COURSE1+2024"]},
4362+
}
4363+
with patch("openedx_authz.rest_api.v1.views.get_waffle_flag_states", return_value=flag_states):
4364+
response = self.client.get(self.url)
4365+
4366+
self.assertEqual(response.status_code, status.HTTP_200_OK)
4367+
self.assertEqual(response.data, flag_states)
4368+
4369+
def test_get_handles_an_unexpected_error(self):
4370+
"""Test GET /waffle-flag-states/ when get_waffle_flag_states raises.
4371+
4372+
Expected result:
4373+
- Returns 500 INTERNAL SERVER ERROR status with a generic error message.
4374+
"""
4375+
with patch("openedx_authz.rest_api.v1.views.get_waffle_flag_states", side_effect=Exception("boom")):
4376+
response = self.client.get(self.url)
4377+
4378+
self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
4379+
self.assertEqual(response.data, {"message": "error"})
4380+
4381+
def test_get_requires_authentication(self):
4382+
"""Test GET /waffle-flag-states/ without authentication.
4383+
4384+
Expected result:
4385+
- Returns 401 UNAUTHORIZED status.
4386+
"""
4387+
self.client.force_authenticate(user=None)
4388+
4389+
response = self.client.get(self.url)
4390+
4391+
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

openedx_authz/tests/test_utils.py

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
"""Test utilities for creating namespaced keys using class constants."""
22

3+
from types import SimpleNamespace
4+
from unittest.mock import MagicMock, patch
5+
6+
from ddt import data, ddt, unpack
7+
from django.test import TestCase
8+
39
from openedx_authz.api.data import (
410
GLOBAL_SCOPE_WILDCARD,
511
ActionData,
@@ -9,6 +15,9 @@
915
ScopeData,
1016
UserData,
1117
)
18+
from openedx_authz.utils import get_waffle_flag_states
19+
20+
FLAG_NAME = "authz.enable_course_authoring"
1221

1322

1423
def make_policy(role_key: str, action_key: str, scope_key: str, effect: str = "allow") -> list[str]:
@@ -187,3 +196,129 @@ def make_wildcard_key(namespace: str) -> str:
187196
str: Wildcard pattern (e.g., 'lib^*', 'org^*', 'course^*')
188197
"""
189198
return f"{namespace}{ScopeData.SEPARATOR}{GLOBAL_SCOPE_WILDCARD}"
199+
200+
201+
@ddt
202+
class TestGetWaffleFlagStates(TestCase):
203+
"""Test get_waffle_flag_states, which reports the course-authoring flag's state at each tier."""
204+
205+
def _mock_override_model(self, override_rows: list):
206+
"""Build a mock override model. override_rows is a list of (key, override_choice) tuples."""
207+
mock_model = MagicMock()
208+
mock_model.objects.current_set.return_value.filter.return_value.values_list.return_value = override_rows
209+
return mock_model
210+
211+
@data(True, False)
212+
def test_global_tier_follows_the_platform_flag(self, platform_enabled: bool):
213+
"""Test get_waffle_flag_states' global key.
214+
215+
Expected result:
216+
- Matches global waffle flag result.
217+
"""
218+
with patch(
219+
"openedx_authz.utils.Flag",
220+
MagicMock(objects=MagicMock(
221+
filter=MagicMock(return_value=MagicMock(first=MagicMock(
222+
return_value=SimpleNamespace(everyone=platform_enabled)
223+
)))
224+
)),
225+
), patch(
226+
"openedx_authz.utils.AUTHZ_COURSE_AUTHORING_FLAG", SimpleNamespace(name=FLAG_NAME)
227+
), patch(
228+
"openedx_authz.utils.WaffleFlagOrgOverrideModel", self._mock_override_model([])
229+
), patch(
230+
"openedx_authz.utils.WaffleFlagCourseOverrideModel", self._mock_override_model([])
231+
):
232+
self.assertEqual(get_waffle_flag_states()["global"], platform_enabled)
233+
234+
@data(
235+
([("Org1", "on")], {"on": ["Org1"], "off": []}),
236+
([("Org1", "off")], {"on": [], "off": ["Org1"]}),
237+
([("Org1", "on"), ("Org2", "off")], {"on": ["Org1"], "off": ["Org2"]}),
238+
([], {"on": [], "off": []}),
239+
)
240+
@unpack
241+
def test_org_tier_splits_active_overrides_by_choice(self, override_rows: list, expected: dict):
242+
"""Test get_waffle_flag_states' org key.
243+
244+
Expected result:
245+
- Orgs with an enabled override are split into 'on' and 'off' lists,
246+
by the override's choice.
247+
"""
248+
with patch(
249+
"openedx_authz.utils.Flag",
250+
MagicMock(objects=MagicMock(
251+
filter=MagicMock(return_value=MagicMock(first=MagicMock(
252+
return_value=SimpleNamespace(everyone=False)
253+
)))
254+
)),
255+
), patch(
256+
"openedx_authz.utils.AUTHZ_COURSE_AUTHORING_FLAG", SimpleNamespace(name=FLAG_NAME)
257+
), patch(
258+
"openedx_authz.utils.WaffleFlagOrgOverrideModel", self._mock_override_model(override_rows)
259+
), patch(
260+
"openedx_authz.utils.WaffleFlagCourseOverrideModel", self._mock_override_model([])
261+
):
262+
self.assertEqual(get_waffle_flag_states()["org_overrides"], expected)
263+
264+
@data(
265+
([("course-v1:Org1+COURSE1+2024", "on")], {"on": ["course-v1:Org1+COURSE1+2024"], "off": []}),
266+
([("course-v1:Org1+COURSE1+2024", "off")], {"on": [], "off": ["course-v1:Org1+COURSE1+2024"]}),
267+
(
268+
[("course-v1:Org1+COURSE1+2024", "on"), ("course-v1:Org1+COURSE2+2024", "off")],
269+
{"on": ["course-v1:Org1+COURSE1+2024"], "off": ["course-v1:Org1+COURSE2+2024"]},
270+
),
271+
([], {"on": [], "off": []}),
272+
)
273+
@unpack
274+
def test_course_tier_splits_active_overrides_by_choice(self, override_rows: list, expected: dict):
275+
"""Test get_waffle_flag_states' course key.
276+
277+
Expected result:
278+
- Courses with an enabled override are split into 'on' and 'off' lists,
279+
by the override's choice. Course keys are stringified.
280+
"""
281+
with patch(
282+
"openedx_authz.utils.Flag",
283+
MagicMock(objects=MagicMock(
284+
filter=MagicMock(return_value=MagicMock(first=MagicMock(
285+
return_value=SimpleNamespace(everyone=False)
286+
)))
287+
)),
288+
), patch(
289+
"openedx_authz.utils.AUTHZ_COURSE_AUTHORING_FLAG", SimpleNamespace(name=FLAG_NAME)
290+
), patch(
291+
"openedx_authz.utils.WaffleFlagOrgOverrideModel", self._mock_override_model([])
292+
), patch(
293+
"openedx_authz.utils.WaffleFlagCourseOverrideModel", self._mock_override_model(override_rows)
294+
):
295+
self.assertEqual(get_waffle_flag_states()["course_overrides"], expected)
296+
297+
def test_all_three_tiers_are_independent(self):
298+
"""Test get_waffle_flag_states with each tier in a different state.
299+
300+
Expected result:
301+
- Each key reflects only its own tier, not a blend of the others.
302+
"""
303+
with patch(
304+
"openedx_authz.utils.Flag",
305+
MagicMock(objects=MagicMock(
306+
filter=MagicMock(return_value=MagicMock(first=MagicMock(
307+
return_value=SimpleNamespace(everyone=False)
308+
)))
309+
)),
310+
), patch(
311+
"openedx_authz.utils.AUTHZ_COURSE_AUTHORING_FLAG", SimpleNamespace(name=FLAG_NAME)
312+
), patch(
313+
"openedx_authz.utils.WaffleFlagOrgOverrideModel", self._mock_override_model([("Org1", "on")])
314+
), patch(
315+
"openedx_authz.utils.WaffleFlagCourseOverrideModel", self._mock_override_model([])
316+
):
317+
self.assertEqual(
318+
get_waffle_flag_states(),
319+
{
320+
"global": False,
321+
"org_overrides": {"on": ["Org1"], "off": []},
322+
"course_overrides": {"on": [], "off": []},
323+
},
324+
)

0 commit comments

Comments
 (0)