Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
realm: Add option to enable/disable spectator login.
Aman Agrawal2a922409aae7
diff --git a/static/js/admin.js b/static/js/admin.jsindex fd53cd04583..b5a6277531c 100644--- a/static/js/admin.js+++ b/static/js/admin.js@@ -28,6 +28,9 @@ const admin_settings_label = {realm_message_content_allowed_in_email_notifications: $t({defaultMessage: "Allow message content in message notification emails",}),+ realm_enable_spectator_access: $t({+ defaultMessage: "Allow creating web-public streams (visible to anyone on the Internet)",+ }),realm_digest_emails_enabled: $t({defaultMessage: "Send weekly digest emails to inactive users",}),@@ -119,6 +122,7 @@ export function build_page() {realm_send_welcome_emails: page_params.realm_send_welcome_emails,realm_message_content_allowed_in_email_notifications:page_params.realm_message_content_allowed_in_email_notifications,+ realm_enable_spectator_access: page_params.realm_enable_spectator_access,settings_send_digest_emails: page_params.settings_send_digest_emails,realm_digest_emails_enabled: page_params.realm_digest_emails_enabled,realm_digest_weekday: page_params.realm_digest_weekday,diff --git a/static/js/server_events_dispatch.js b/static/js/server_events_dispatch.jsindex 41455435e84..0abc45ca155 100644--- a/static/js/server_events_dispatch.js+++ b/static/js/server_events_dispatch.js@@ -214,6 +214,7 @@ export function dispatch_normal_event(event) {private_message_policy: noop,send_welcome_emails: noop,message_content_allowed_in_email_notifications: noop,+ realm_enable_spectator_access: noop,signup_notifications_stream_id: noop,emails_restricted_to_domains: noop,video_chat_provider: compose.update_video_chat_button_display,diff --git a/static/templates/settings/organization_permissions_admin.hbs b/static/templates/settings/organization_permissions_admin.hbsindex f19c60e62f3..4fbe0dd3041 100644--- a/static/templates/settings/organization_permissions_admin.hbs+++ b/static/templates/settings/organization_permissions_admin.hbs@@ -103,6 +103,12 @@{{> dropdown_options_widget option_values=common_policy_values}}</select></div>+ {{> settings_checkbox+ setting_name="realm_enable_spectator_access"+ prefix="id_"+ is_checked=realm_enable_spectator_access+ render_only=page_params.development_environment+ label=admin_settings_label.realm_enable_spectator_access}}<div class="input-group"><label for="realm_create_private_stream_policy" class="dropdown-title">{{t "Who can create private streams" }}</label><select name="realm_create_private_stream_policy" id="id_realm_create_private_stream_policy" class="prop-element" data-setting-widget-type="number">diff --git a/templates/zerver/api/changelog.md b/templates/zerver/api/changelog.mdindex 5df9588c295..4e2484cbea7 100644--- a/templates/zerver/api/changelog.md+++ b/templates/zerver/api/changelog.md@@ -20,6 +20,12 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 5.0+**Feature level 109**++* [`POST /register`](/api/register-queue), [`GET+ /events`](/api/get-events), `PATCH /realm`: Added new+ `enable_spectator_access` realm setting.+**Feature level 108*** In the mobile application authentication flow, the authenticateddiff --git a/version.py b/version.pyindex dcef96954fa..cfe50a70ba8 100644--- a/version.py+++ b/version.py@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.4.3"# Changes should be accompanied by documentation explaining what the# new level means in templates/zerver/api/changelog.md, as well as# "**Changes**" entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 108+API_FEATURE_LEVEL = 109# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/context_processors.py b/zerver/context_processors.pyindex d4a8596590d..fffcda85329 100644--- a/zerver/context_processors.py+++ b/zerver/context_processors.py@@ -194,7 +194,7 @@ def login_context(request: HttpRequest) -> Dict[str, Any]:realm_invite_required = realm.invite_required# We offer web public access only if the realm has actual web# public streams configured, in addition to having it enabled.- realm_web_public_access_enabled = realm.has_web_public_streams()+ realm_web_public_access_enabled = realm.allow_web_public_streams_access()context: Dict[str, Any] = {"realm_invite_required": realm_invite_required,diff --git a/zerver/migrations/0370_realm_enable_spectator_access.py b/zerver/migrations/0370_realm_enable_spectator_access.pynew file mode 100644index 00000000000..175fe8f4d9a--- /dev/null+++ b/zerver/migrations/0370_realm_enable_spectator_access.py@@ -0,0 +1,18 @@+# Generated by Django 3.2.7 on 2021-10-06 11:42++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("zerver", "0369_add_escnav_default_display_user_setting"),+ ]++ operations = [+ migrations.AddField(+ model_name="realm",+ name="enable_spectator_access",+ field=models.BooleanField(default=False),+ ),+ ]diff --git a/zerver/models.py b/zerver/models.pyindex fdf3520f049..a9071f5014f 100644--- a/zerver/models.py+++ b/zerver/models.py@@ -240,6 +240,10 @@ class Realm(models.Model):default=2 ** 31 - 1,)+ # Allow users to access web public streams without login. This+ # setting also controls API access of web public streams.+ enable_spectator_access: bool = models.BooleanField(default=False)+# Whether the organization has enabled inline image and URL previews.inline_image_preview: bool = models.BooleanField(default=True)inline_url_embed_preview: bool = models.BooleanField(default=False)@@ -639,6 +643,7 @@ class Realm(models.Model):email_address_visibility=int,email_changes_disabled=bool,emails_restricted_to_domains=bool,+ enable_spectator_access=bool,giphy_rating=int,inline_image_preview=bool,inline_url_embed_preview=bool,@@ -894,10 +899,6 @@ class Realm(models.Model):return Truedef has_web_public_streams(self) -> bool:- """- If any of the streams in the realm is web- public, then the realm is web public.- """if not self.web_public_streams_enabled():return False@@ -905,6 +906,14 @@ class Realm(models.Model):return get_web_public_streams_queryset(self).exists()+ def allow_web_public_streams_access(self) -> bool:+ """+ If any of the streams in the realm is web+ public and `enable_spectator_access` is True,+ then the Realm is web public.+ """+ return self.enable_spectator_access and self.has_web_public_streams()+post_save.connect(flush_realm, sender=Realm)diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 8e5a36f7b00..34a4c7b2bc4 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -3530,6 +3530,19 @@ paths:Whether [new users joining](/help/allow-anyone-to-join-without-an-invitation)this organization are required to have an emailaddress in one of the `realm_domains` configured for the organization.+ enable_spectator_access:+ type: boolean+ description: |+ Whether web public streams are enabled in this organization.++ Can only be enabled if the `WEB_PUBLIC_STREAMS_ENABLED`+ [server setting][server-settings] is enabled on the Zulip+ server. See also the `create_web_public_stream_policy` realm+ setting.++ [server-settings]: https://zulip.readthedocs.io/en/stable/production/settings.html++ **Changes**: New in Zulip 5.0 (feature level 109).giphy_rating:type: integerdescription: |@@ -6629,7 +6642,10 @@ paths:Note that creating web public streams requires the`WEB_PUBLIC_STREAMS_ENABLED` [server setting][server-settings]- to be enabled on the Zulip server in question.+ to be enabled on the Zulip server in question, the organization+ to have enabled the `enable_spectator_access` realm setting, and+ the current use to have permission under the organization's+ `create_web_public_stream_policy` realm setting.[server-settings]: https://zulip.readthedocs.io/en/stable/production/settings.html@@ -10379,7 +10395,8 @@ paths:Has no effect and should not be displayed in settings UIunless the Zulip server has the `WEB_PUBLIC_STREAMS_ENABLED`- server-level setting enabled.+ server-level setting enabled and the organization has enabled+ the `enable_spectator_access` realm setting.The policy for which users can create webpublic streams in this organization. Allowed@@ -10582,6 +10599,20 @@ paths:Whether notification emails in this organization are allowed tocontain Zulip the message content, or simply indicate that a newmessage was sent.+ realm_enable_spectator_access:+ type: boolean+ description: |+ Present if `realm` is present in `fetch_event_types`.++ Whether web public streams and related anonymous access APIs/features+ are enabled in this organization.++ Can only be enabled if the `WEB_PUBLIC_STREAMS_ENABLED`+ [server setting][server-settings] is enabled on the Zulip+ server. See also the `create_web_public_stream_policy` realm+ setting.++ **Changes**: New in Zulip 5.0 (feature level 109).realm_video_chat_provider:type: integerdescription: |@@ -11466,7 +11497,8 @@ paths:the organization's [stream creation policy](/help/configure-who-can-create-streams).Note that this will be false if the Zulip server does not have the- `WEB_PUBLIC_STREAMS_ENABLED` setting enabled.+ `WEB_PUBLIC_STREAMS_ENABLED` setting enabled or if the organization has+ not enabled the `enable_spectator_access` realm setting.**Changes**: New in Zulip 5.0 (feature level 103).can_subscribe_other_users:@@ -12811,7 +12843,10 @@ paths:Note that creating web public streams requires the`WEB_PUBLIC_STREAMS_ENABLED` [server setting][server-settings]- to be enabled on the Zulip server in question.+ to be enabled on the Zulip server in question, the organization+ to have enabled the `enable_spectator_access` realm setting, and+ the current use to have permission under the organization's+ `create_web_public_stream_policy` realm setting.[server-settings]: https://zulip.readthedocs.io/en/stable/production/settings.htmldiff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex c346468ff37..6529cb0cb0d 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -136,6 +136,7 @@ class HomeTest(ZulipTestCase):"realm_emails_restricted_to_domains","realm_embedded_bots","realm_emoji",+ "realm_enable_spectator_access","realm_filters","realm_giphy_rating","realm_icon_source",@@ -312,8 +313,22 @@ class HomeTest(ZulipTestCase):self.assertEqual(result.url, "/login/")# Tell server that user wants to login anonymously- # Redirects to load webapp.+ # Redirects to load webapp. Since Realm.enable_spectator_access+ # is False, the login should fail.+ realm = get_realm("zulip")result = self.client_post("/", {"prefers_web_public_view": "true"})+ self.assertEqual(self.client.session.get("prefers_web_public_view"), None)+ self.assertEqual(realm.enable_spectator_access, False)+ self.assertEqual(result.status_code, 302)+ self.assertEqual(result.url, "/login/")++ # Enable spectator login.+ realm.enable_spectator_access = True+ realm.save()++ result = self.client_post("/", {"prefers_web_public_view": "true"})+ self.assertEqual(self.client.session.get("prefers_web_public_view"), True)+ self.assertEqual(realm.enable_spectator_access, True)self.assertEqual(result.status_code, 302)self.assertEqual(result.url, "http://zulip.testserver")@@ -337,6 +352,9 @@ class HomeTest(ZulipTestCase):self.client_get("/")self.assertEqual(self.client.session.get("prefers_web_public_view"), None)+ realm.enable_spectator_access = False+ realm.save()+def test_home_under_2fa_without_otp_device(self) -> None:with self.settings(TWO_FACTOR_AUTHENTICATION_ENABLED=True):self.login("iago")diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex 1fad464a5d4..2577b44dc68 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -1491,6 +1491,7 @@ class GetOldMessagesTest(ZulipTestCase):An unauthenticated call to GET /json/messages with valid parametersreturns a 401."""+ do_set_realm_property(get_realm("zulip"), "enable_spectator_access", True, acting_user=None)post_params = {"anchor": 1,"num_before": 1,@@ -1517,6 +1518,7 @@ class GetOldMessagesTest(ZulipTestCase):An unauthenticated call to GET /json/messages without validparameters in the `streams:web-public` narrow returns a 401."""+ do_set_realm_property(get_realm("zulip"), "enable_spectator_access", True, acting_user=None)post_params: Dict[str, Union[int, str, bool]] = {"anchor": 1,"num_before": 1,@@ -1534,10 +1536,35 @@ class GetOldMessagesTest(ZulipTestCase):result, "Not logged in: API authentication or user session required", status_code=401)+ def test_unauthenticated_get_messages_disabled_spectator_login(self) -> None:+ """+ An unauthenticated call to GET /json/messages without valid+ parameters in the `streams:web-public` narrow returns a 401.+ """+ do_set_realm_property(+ get_realm("zulip"), "enable_spectator_access", False, acting_user=None+ )+ post_params: Dict[str, Union[int, str, bool]] = {+ "anchor": 1,+ "num_before": 1,+ "num_after": 1,+ "narrow": orjson.dumps(+ [+ dict(operator="streams", operand="web-public"),+ dict(operator="stream", operand="Scotland"),+ ]+ ).decode(),+ }+ result = self.client_get("/json/messages", dict(post_params))+ self.assert_json_error(+ result, "Not logged in: API authentication or user session required", status_code=401+ )+def test_unauthenticated_narrow_to_non_web_public_streams_without_web_public(self) -> None:"""An unauthenticated call to GET /json/messages without `streams:web-public` narrow returns a 401."""+ do_set_realm_property(get_realm("zulip"), "enable_spectator_access", True, acting_user=None)post_params: Dict[str, Union[int, str, bool]] = {"anchor": 1,"num_before": 1,@@ -1555,6 +1582,7 @@ class GetOldMessagesTest(ZulipTestCase):parameters in the `streams:web-public` narrow + narrow to stream returnsa 400 if the target stream is not web-public."""+ do_set_realm_property(get_realm("zulip"), "enable_spectator_access", True, acting_user=None)post_params: Dict[str, Union[int, str, bool]] = {"anchor": 1,"num_before": 1,@@ -1577,6 +1605,9 @@ class GetOldMessagesTest(ZulipTestCase):and then a private message."""user_profile = self.example_user("iago")+ do_set_realm_property(+ user_profile.realm, "enable_spectator_access", True, acting_user=user_profile+ )self.login("iago")web_public_stream = self.make_stream("web-public-stream", is_web_public=True)non_web_public_stream = self.make_stream("non-web-public-stream")diff --git a/zerver/views/home.py b/zerver/views/home.pyindex 802e2c5c4c8..f9be1394308 100644--- a/zerver/views/home.py+++ b/zerver/views/home.py@@ -8,7 +8,7 @@ from django.shortcuts import redirect, renderfrom django.utils.cache import patch_cache_controlfrom zerver.context_processors import get_valid_realm_from_request-from zerver.decorator import web_public_view, zulip_login_required, zulip_redirect_to_login+from zerver.decorator import web_public_view, zulip_login_requiredfrom zerver.forms import ToSFormfrom zerver.lib.actions import do_change_tos_version, realm_user_countfrom zerver.lib.compatibility import is_outdated_desktop_app, is_unsupported_browser@@ -102,20 +102,25 @@ def update_last_reminder(user_profile: Optional[UserProfile]) -> None:def home(request: HttpRequest) -> HttpResponse:- if not settings.ROOT_DOMAIN_LANDING_PAGE:- return home_real(request)-- # If settings.ROOT_DOMAIN_LANDING_PAGE, sends the user the landing- # page, not the login form, on the root domain-subdomain = get_subdomain(request)- if subdomain != Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:- return home_real(request)- return hello_view(request)+ # If settings.ROOT_DOMAIN_LANDING_PAGE and this is the root+ # domain, send the user the landing page.+ if settings.ROOT_DOMAIN_LANDING_PAGE and subdomain == Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:+ return hello_view(request)++ # TODO: The following logic is a bit hard to read. We save a+ # database query in the common case by avoiding the call to+ # `get_valid_realm_from_request` if user hasn't requested+ # web-public access.+ if (+ request.POST.get("prefers_web_public_view") == "true"+ or request.session.get("prefers_web_public_view")+ ) and get_valid_realm_from_request(request).allow_web_public_streams_access():+ return web_public_view(home_real)(request)+ return zulip_login_required(home_real)(request)-@web_public_viewdef home_real(request: HttpRequest) -> HttpResponse:# Before we do any real work, check if the app is banned.client_user_agent = request.META.get("HTTP_USER_AGENT", "")@@ -169,11 +174,8 @@ def home_real(request: HttpRequest) -> HttpResponse:redirect_to = get_safe_redirect_to(request.POST.get("next"), realm.uri)return redirect(redirect_to)- prefers_web_public_view = request.session.get("prefers_web_public_view")- if not prefers_web_public_view:- # For users who haven't opted into the spectator- # experience, we redirect to the login page.- return zulip_redirect_to_login(request, settings.HOME_NOT_LOGGED_IN)+ # See the assert in `home` above for why this must be true.+ assert request.session.get("prefers_web_public_view")# For users who have selected public access, we load the# spectator experience. We fall through to the shared codediff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.pyindex b4ecf120316..f0457e397f8 100644--- a/zerver/views/message_fetch.py+++ b/zerver/views/message_fetch.py@@ -958,6 +958,7 @@ def get_messages_backend())+ realm = get_valid_realm_from_request(request)if not maybe_user_profile.is_authenticated:# If user is not authenticated, clients must include# `streams:web-public` in their narrow query to indicate this@@ -969,13 +970,14 @@ def get_messages_backend(# GetOldMessagesTest.test_unauthenticated_* tests ensure# that we are not leaking any secure data (private messages and# non web-public-stream messages) via this path.+ if not realm.allow_web_public_streams_access():+ raise MissingAuthenticationError()if not is_web_public_narrow(narrow):raise MissingAuthenticationError()assert narrow is not Noneif not is_spectator_compatible(narrow):raise MissingAuthenticationError()- realm = get_valid_realm_from_request(request)# We use None to indicate unauthenticated requests as it's more# readable than using AnonymousUser, and the lack of Django# stubs means that mypy can't check AnonymousUser well.@@ -985,7 +987,6 @@ def get_messages_backend(assert isinstance(maybe_user_profile, UserProfile)user_profile = maybe_user_profileassert user_profile is not None- realm = user_profile.realmis_web_public_query = Falseassert realm is not Nonediff --git a/zerver/views/realm.py b/zerver/views/realm.pyindex 00f11a52b37..073d69b47fe 100644--- a/zerver/views/realm.py+++ b/zerver/views/realm.py@@ -138,6 +138,7 @@ def update_realm(str_validator=check_capped_string(Realm.MAX_REALM_SUBDOMAIN_LENGTH),default=None,),+ enable_spectator_access: Optional[bool] = REQ(json_validator=check_bool, default=None),) -> HttpResponse:realm = user_profile.realmdiff --git a/zerver/views/users.py b/zerver/views/users.pyindex db75d0c7ba2..2894b60da15 100644--- a/zerver/views/users.py+++ b/zerver/views/users.py@@ -238,9 +238,7 @@ def avatar(# Allow anonynous access to avatars only if spectators are# enabled in the organization.realm = get_valid_realm_from_request(request)- # TODO: Replace with realm.allow_web_public_streams_access()- # when the method is available.- if not realm.has_web_public_streams():+ if not realm.allow_web_public_streams_access():raise MissingAuthenticationError()# We only allow the ID format for accessing a user's avatar