Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
scim: Override django-scim2 logic of exception handling in views.
Mateusz Manderaf5a65846a829
diff --git a/zerver/lib/scim.py b/zerver/lib/scim.pyindex 50e7cf5637f..97e81c37583 100644--- a/zerver/lib/scim.py+++ b/zerver/lib/scim.py@@ -2,11 +2,17 @@ from typing import Any, Callable, Dict, List, Optional, Type, Unionimport django_scim.constants as scim_constantsimport django_scim.exceptions as scim_exceptions+import orjsonfrom django.conf import settings+from django.contrib.auth.decorators import login_requiredfrom django.core.exceptions import ValidationErrorfrom django.db import models, transaction-from django.http import HttpRequest+from django.http import HttpRequest, HttpResponse+from django.utils.decorators import method_decorator+from django.views.decorators.csrf import csrf_exemptfrom django_scim.adapters import SCIMUser+from django_scim.views import SCIMView, SearchView, UserSearchView, UsersView+from django_scim.views import logger as scim_views_loggerfrom scim2_filter_parser.attr_paths import AttrPathfrom zerver.lib.actions import (@@ -361,3 +367,58 @@ class ConflictError(scim_exceptions.IntegrityError):"""scim_type = "uniqueness"+++class ZulipSCIMViewMixin(SCIMView):+ """+ Default django-scim2 behavior is to convert any exception that occurs while processing+ the request within the view code to a string and put it+ in the HttpResponse. We don't want that due to the risk of leaking sensitive information+ through the error message.++ The way we implement this override is by having this mixin override the main dispatch()+ method - and then all the specific view classes are re-defined to inherit from this mixin+ and the original django-scim2 class. This means that we have to also re-register all+ the URL patterns so that our View classes are used.+ """++ @method_decorator(csrf_exempt)+ @method_decorator(login_required)+ def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:+ """+ This method through which all SCIM views are processed needs to be forked+ to change its logic of how exceptions are handled.+ """+ if not self.implemented:+ return self.status_501(request, *args, **kwargs)++ try:+ return super(SCIMView, self).dispatch(request, *args, **kwargs)+ except Exception as e:+ if not isinstance(e, scim_exceptions.SCIMException):+ # This is where we adjust the exception-handling behavior. Instead of+ # putting str(e) in the response, we use a generic error that won't leak+ # information.+ scim_views_logger.exception("Unable to complete SCIM call.")+ e = scim_exceptions.SCIMException("Exception while processing SCIM request.")++ content = orjson.dumps(e.to_dict())+ return HttpResponse(+ content=content, content_type=scim_constants.SCIM_CONTENT_TYPE, status=e.status+ )+++class ZulipSCIMView(ZulipSCIMViewMixin, SCIMView):+ pass+++class ZulipSCIMUsersView(ZulipSCIMViewMixin, UsersView):+ pass+++class ZulipSCIMSearchView(ZulipSCIMViewMixin, SearchView):+ pass+++class ZulipSCIMUserSearchView(ZulipSCIMViewMixin, UserSearchView):+ passdiff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.pyindex 81fa75f397b..5e1d2a618b6 100644--- a/zerver/lib/test_helpers.py+++ b/zerver/lib/test_helpers.py@@ -493,6 +493,13 @@ def write_instrumentation_reports(full_suite: bool, include_webhooks: bool) -> N# We actually test them, but it's not being detected as a tested pattern,# possibly due to the use of re_path. TODO: Investigate and get them# recognized as tested.+ "scim/v2/",+ "scim/v2/.search",+ "scim/v2/Bulk",+ "scim/v2/Me",+ "scim/v2/ResourceTypes(?:/(?P<uuid>[^/]+))?",+ "scim/v2/Schemas(?:/(?P<uuid>[^/]+))?",+ "scim/v2/ServiceProviderConfig","scim/v2/Groups(?:/(?P<uuid>[^/]+))?","scim/v2/Groups/.search",*(webhook.url for webhook in WEBHOOK_INTEGRATIONS if not include_webhooks),diff --git a/zerver/tests/test_scim.py b/zerver/tests/test_scim.pyindex 01b1815cde3..e764d394380 100644--- a/zerver/tests/test_scim.py+++ b/zerver/tests/test_scim.py@@ -84,6 +84,32 @@ class TestNonSCIMAPIAccess(SCIMTestCase):self.assert_json_error(result, "This endpoint requires HTTP basic authentication.", 400)+class TestExceptionDetailsNotRevealedToClient(SCIMTestCase):+ def test_exception_details_not_revealed_to_client(self) -> None:+ """+ Verify that, unlike in default django-scim2 behavior, details of an exception+ are not revealed in the HttpResponse.+ """+ with mock.patch(+ "zerver.lib.scim.ZulipSCIMUser.to_dict", side_effect=Exception("test exception")+ ), self.assertLogs("django_scim.views", "ERROR") as mock_scim_logger, self.assertLogs(+ "django.request", "ERROR"+ ) as mock_request_logger:+ result = self.client_get("/scim/v2/Users", **self.scim_headers())+ # Only a generic error message is returned:+ self.assertEqual(+ result.json(),+ {+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],+ "detail": "Exception while processing SCIM request.",+ "status": 500,+ },+ )+ # Details of the exception still get internally logged as expected:+ self.assertIn("test exception", mock_scim_logger.output[0])+ self.assertIn("Internal Server Error: /scim/v2/Users", mock_request_logger.output[0])++class TestSCIMUser(SCIMTestCase):def test_get_by_id(self) -> None:hamlet = self.example_user("hamlet")@@ -645,3 +671,20 @@ class TestSCIMGroup(SCIMTestCase):self.assertEqual(m.output, ["ERROR:django.request:Not Implemented: /scim/v2/Groups/.search"])+++class TestRemainingUnsupportedSCIMFeatures(SCIMTestCase):+ def test_endpoints_disabled(self) -> None:+ for url in [+ "/scim/v2/",+ "/scim/v2/.search",+ "/scim/v2/Bulk",+ "/scim/v2/Me",+ "/scim/v2/ResourceTypes",+ "/scim/v2/Schemas",+ "/scim/v2/ServiceProviderConfig",+ ]:+ with self.assertLogs("django.request", "ERROR") as m:+ result = self.client_get(url, **self.scim_headers())+ self.assertEqual(result.status_code, 501)+ self.assertEqual(m.output, [f"ERROR:django.request:Not Implemented: {url}"])diff --git a/zproject/urls.py b/zproject/urls.pyindex f433dfbef36..4b7516962b3 100644--- a/zproject/urls.py+++ b/zproject/urls.py@@ -742,19 +742,45 @@ urls += [path("saml/metadata.xml", saml_sp_metadata)]# SCIM2-from django_scim import views as scim_views+from zerver.lib.scim import (+ ZulipSCIMSearchView,+ ZulipSCIMUserSearchView,+ ZulipSCIMUsersView,+ ZulipSCIMView,+)urls += [- # These first couple entries mark the Groups feature of SCIM as- # something we haven't implemented.+ # We have to register all the SCIM URL patterns first, because we override+ # all the SCIM View classes and we need Django to use them instead of+ # the django-scim2 Views that the app will register.+ re_path(r"^scim/v2/$", ZulipSCIMView.as_view(implemented=False)),+ re_path(r"^scim/v2/.search$", ZulipSCIMSearchView.as_view(implemented=False)),+ re_path(r"^scim/v2/Users/.search$", ZulipSCIMUserSearchView.as_view()),+ re_path(r"^scim/v2/Users(?:/(?P<uuid>[^/]+))?$", ZulipSCIMUsersView.as_view()),+ # Everything below here are features that we don't yet support and we want+ # to explicitly mark them to return "Not Implemented" rather than running+ # the django-scim2 code for them.re_path(r"^scim/v2/Groups/.search$",- scim_views.SCIMView.as_view(implemented=False),+ ZulipSCIMView.as_view(implemented=False),),re_path(r"^scim/v2/Groups(?:/(?P<uuid>[^/]+))?$",- scim_views.SCIMView.as_view(implemented=False),+ ZulipSCIMView.as_view(implemented=False),+ ),+ re_path(r"^scim/v2/Me$", ZulipSCIMView.as_view(implemented=False)),+ re_path(+ r"^scim/v2/ServiceProviderConfig$",+ ZulipSCIMView.as_view(implemented=False),+ ),+ re_path(+ r"^scim/v2/ResourceTypes(?:/(?P<uuid>[^/]+))?$",+ ZulipSCIMView.as_view(implemented=False),),+ re_path(r"^scim/v2/Schemas(?:/(?P<uuid>[^/]+))?$", ZulipSCIMView.as_view(implemented=False)),+ re_path(r"^scim/v2/Bulk$", ZulipSCIMView.as_view(implemented=False)),+ # At the end we still register the django-scim2 url patterns (even though we override them all above)+ # so that reverse("scim:viewname") still works like the internal library code expects.path("scim/v2/", include("django_scim.urls", namespace="scim")),]