Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

message: Use new setting for checking stream posting permissions.

Sahil Batra2d09cd899ee7
diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.py
index 2c0e136e2ac..a2c7d4d4429 100644
--- a/tools/linter_lib/custom_check.py
+++ b/tools/linter_lib/custom_check.py
@@ -379,11 +379,6 @@ python_rules = RuleList(
{
"pattern": "get_stream[(]",
"include_only": {"zerver/views/", "zerver/actions/"},
- "exclude_line": {
- # This one in check_message is kinda terrible, since it's
- # how most instances are written, but better to exclude something than nothing
- ("zerver/actions/message_send.py", "stream = get_stream(stream_name, realm)"),
- },
"description": "Please use access_stream_by_*() to fetch Stream objects",
},
{
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.py
index 7184b3f5854..0f237e6aa04 100644
--- a/zerver/actions/message_edit.py
+++ b/zerver/actions/message_edit.py
@@ -49,8 +49,9 @@ from zerver.lib.stream_subscription import get_active_subscriptions_for_stream_i
from zerver.lib.stream_topic import StreamTopicTarget
from zerver.lib.streams import (
access_stream_by_id,
+ access_stream_by_id_for_message,
can_access_stream_history,
- check_stream_access_based_on_stream_post_policy,
+ check_stream_access_based_on_can_send_message_group,
)
from zerver.lib.string_validation import check_stream_topic
from zerver.lib.timestamp import datetime_to_timestamp
@@ -1354,8 +1355,10 @@ def check_update_message(
if not user_profile.can_move_messages_between_streams():
raise JsonableError(_("You don't have permission to move this message"))
- new_stream = access_stream_by_id(user_profile, stream_id, require_active=True)[0]
- check_stream_access_based_on_stream_post_policy(user_profile, new_stream)
+ new_stream = access_stream_by_id_for_message(user_profile, stream_id, require_active=True)[
+ 0
+ ]
+ check_stream_access_based_on_can_send_message_group(user_profile, new_stream)
if (
user_profile.realm.move_messages_between_streams_limit_seconds is not None
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py
index 75e217e2015..ce8a2eb105b 100644
--- a/zerver/actions/message_send.py
+++ b/zerver/actions/message_send.py
@@ -98,7 +98,10 @@ from zerver.models.clients import get_client
from zerver.models.groups import SystemGroups
from zerver.models.recipients import get_direct_message_group_user_ids
from zerver.models.scheduled_jobs import NotificationTriggers
-from zerver.models.streams import get_stream, get_stream_by_id_in_realm
+from zerver.models.streams import (
+ get_stream_by_id_for_sending_message,
+ get_stream_by_name_for_sending_message,
+)
from zerver.models.users import (
active_user_ids,
get_system_bot,
@@ -1542,7 +1545,7 @@ def validate_stream_name_with_pm_notification(
check_stream_name(stream_name)
try:
- stream = get_stream(stream_name, realm)
+ stream = get_stream_by_name_for_sending_message(stream_name, realm)
send_pm_if_empty_stream(stream, realm, sender)
except Stream.DoesNotExist:
send_pm_if_empty_stream(None, realm, sender, stream_name=stream_name)
@@ -1555,7 +1558,7 @@ def validate_stream_id_with_pm_notification(
stream_id: int, realm: Realm, sender: UserProfile
) -> Stream:
try:
- stream = get_stream_by_id_in_realm(stream_id, realm)
+ stream = get_stream_by_id_for_sending_message(stream_id, realm)
send_pm_if_empty_stream(stream, realm, sender)
except Stream.DoesNotExist:
send_pm_if_empty_stream(None, realm, sender, stream_id=stream_id)
diff --git a/zerver/lib/bulk_create.py b/zerver/lib/bulk_create.py
index d89a28d8a32..9bdc59fac5f 100644
--- a/zerver/lib/bulk_create.py
+++ b/zerver/lib/bulk_create.py
@@ -211,23 +211,22 @@ def bulk_create_streams(realm: Realm, stream_dict: dict[str, dict[str, Any]]) ->
)
creator = options.get("creator", None)
if name.lower() not in existing_streams:
- streams_to_create.append(
- Stream(
- realm=realm,
- name=name,
- description=options["description"],
- rendered_description=render_stream_description(options["description"], realm),
- invite_only=options.get("invite_only", False),
- stream_post_policy=options.get(
- "stream_post_policy", Stream.STREAM_POST_POLICY_EVERYONE
- ),
- history_public_to_subscribers=options["history_public_to_subscribers"],
- is_web_public=options.get("is_web_public", False),
- is_in_zephyr_realm=realm.is_zephyr_mirror_realm,
- creator=options.get("creator", None),
- **get_default_values_for_stream_permission_group_settings(realm, creator),
- ),
+ stream = Stream(
+ realm=realm,
+ name=name,
+ description=options["description"],
+ rendered_description=render_stream_description(options["description"], realm),
+ invite_only=options.get("invite_only", False),
+ history_public_to_subscribers=options["history_public_to_subscribers"],
+ is_web_public=options.get("is_web_public", False),
+ is_in_zephyr_realm=realm.is_zephyr_mirror_realm,
+ creator=options.get("creator", None),
+ **get_default_values_for_stream_permission_group_settings(realm, creator),
)
+ if "can_send_message_group" in options:
+ stream.can_send_message_group = options["can_send_message_group"]
+
+ streams_to_create.append(stream)
# Sort streams by name before creating them so that we can have a
# reliable ordering of `stream_id` across different python versions.
# This is required for test fixtures which contain `stream_id`. Prior
diff --git a/zerver/lib/streams.py b/zerver/lib/streams.py
index f7897d00d40..5eaa6d8a646 100644
--- a/zerver/lib/streams.py
+++ b/zerver/lib/streams.py
@@ -48,6 +48,7 @@ from zerver.models.streams import (
bulk_get_streams,
get_realm_stream,
get_stream,
+ get_stream_by_id_for_sending_message,
get_stream_by_id_in_realm,
)
from zerver.models.users import active_non_guest_user_ids, active_user_ids, is_cross_realm_bot_email
@@ -316,25 +317,27 @@ def subscribed_to_stream(user_profile: UserProfile, stream_id: int) -> bool:
).exists()
-def check_stream_access_based_on_stream_post_policy(sender: UserProfile, stream: Stream) -> None:
- if sender.is_realm_admin or is_cross_realm_bot_email(sender.delivery_email):
- pass
- elif stream.stream_post_policy == Stream.STREAM_POST_POLICY_ADMINS:
- raise JsonableError(_("Only organization administrators can send to this channel."))
- elif (
- stream.stream_post_policy == Stream.STREAM_POST_POLICY_MODERATORS
- and not sender.is_moderator
- ):
- raise JsonableError(
- _("Only organization administrators and moderators can send to this channel.")
- )
- elif stream.stream_post_policy != Stream.STREAM_POST_POLICY_EVERYONE and sender.is_guest:
- raise JsonableError(_("Guests cannot send to this channel."))
- elif (
- stream.stream_post_policy == Stream.STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS
- and sender.is_provisional_member
+def check_stream_access_based_on_can_send_message_group(
+ sender: UserProfile, stream: Stream
+) -> None:
+ if is_cross_realm_bot_email(sender.delivery_email):
+ return
+
+ can_send_message_group = stream.can_send_message_group
+ if hasattr(can_send_message_group, "named_user_group"):
+ if can_send_message_group.named_user_group.name == SystemGroups.EVERYONE:
+ return
+
+ if can_send_message_group.named_user_group.name == SystemGroups.NOBODY:
+ raise JsonableError(_("You do not have permission to post in this channel."))
+
+ if not user_has_permission_for_group_setting(
+ stream.can_send_message_group,
+ sender,
+ Stream.stream_permission_group_settings["can_send_message_group"],
+ direct_member_only=False,
):
- raise JsonableError(_("New members cannot send to this channel."))
+ raise JsonableError(_("You do not have permission to post in this channel."))
def access_stream_for_send_message(
@@ -346,10 +349,10 @@ def access_stream_for_send_message(
# Our caller is responsible for making sure that `stream` actually
# matches the realm of the sender.
try:
- check_stream_access_based_on_stream_post_policy(sender, stream)
+ check_stream_access_based_on_can_send_message_group(sender, stream)
except JsonableError as e:
if sender.is_bot and sender.bot_owner is not None:
- check_stream_access_based_on_stream_post_policy(sender.bot_owner, stream)
+ check_stream_access_based_on_can_send_message_group(sender.bot_owner, stream)
else:
raise JsonableError(e.msg)
@@ -546,6 +549,32 @@ def access_stream_by_id(
return (stream, sub)
+def access_stream_by_id_for_message(
+ user_profile: UserProfile,
+ stream_id: int,
+ require_active: bool = True,
+ allow_realm_admin: bool = False,
+) -> tuple[Stream, Subscription | None]:
+ """
+ Variant of access_stream_by_id that uses get_stream_by_id_for_sending_message
+ to ensure we do a select_related("can_send_message_group").
+ """
+ error = _("Invalid channel ID")
+ try:
+ stream = get_stream_by_id_for_sending_message(stream_id, user_profile.realm)
+ except Stream.DoesNotExist:
+ raise JsonableError(error)
+
+ sub = access_stream_common(
+ user_profile,
+ stream,
+ error,
+ require_active=require_active,
+ allow_realm_admin=allow_realm_admin,
+ )
+ return (stream, sub)
+
+
def get_public_streams_queryset(realm: Realm) -> QuerySet[Stream]:
return Stream.objects.filter(realm=realm, invite_only=False, history_public_to_subscribers=True)
diff --git a/zerver/models/streams.py b/zerver/models/streams.py
index 93133674974..4c9b5349545 100644
--- a/zerver/models/streams.py
+++ b/zerver/models/streams.py
@@ -261,6 +261,18 @@ def get_stream_by_id_in_realm(stream_id: int, realm: Realm) -> Stream:
return Stream.objects.select_related("realm", "recipient").get(id=stream_id, realm=realm)
+def get_stream_by_name_for_sending_message(stream_name: str, realm: Realm) -> Stream:
+ return Stream.objects.select_related(
+ "can_send_message_group", "can_send_message_group__named_user_group"
+ ).get(name__iexact=stream_name.strip(), realm_id=realm.id)
+
+
+def get_stream_by_id_for_sending_message(stream_id: int, realm: Realm) -> Stream:
+ return Stream.objects.select_related(
+ "realm", "recipient", "can_send_message_group", "can_send_message_group__named_user_group"
+ ).get(id=stream_id, realm=realm)
+
+
def bulk_get_streams(realm: Realm, stream_names: set[str]) -> dict[str, Any]:
def fetch_streams_by_name(stream_names: set[str]) -> QuerySet[Stream]:
#
diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.py
index ada0047fc2c..3159cac5f4c 100644
--- a/zerver/tests/test_email_mirror.py
+++ b/zerver/tests/test_email_mirror.py
@@ -13,7 +13,7 @@ import orjson
from django.conf import settings
from zerver.actions.realm_settings import do_deactivate_realm
-from zerver.actions.streams import do_change_stream_post_policy, do_deactivate_stream
+from zerver.actions.streams import do_change_stream_group_based_setting, do_deactivate_stream
from zerver.actions.users import do_deactivate_user
from zerver.lib.email_mirror import (
create_missed_message_address,
@@ -39,6 +39,7 @@ from zerver.lib.streams import ensure_stream
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import mock_queue_publish, most_recent_message, most_recent_usermessage
from zerver.models import Attachment, ChannelEmailAddress, Recipient, Stream, UserProfile
+from zerver.models.groups import NamedUserGroup, SystemGroups
from zerver.models.messages import Message
from zerver.models.realms import get_realm
from zerver.models.streams import get_stream
@@ -1182,8 +1183,11 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
self.assert_json_success(result)
stream = get_stream("announce", user_profile.realm)
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_ADMINS, acting_user=user_profile
+ admins_group = NamedUserGroup.objects.get(
+ name=SystemGroups.ADMINISTRATORS, realm=user_profile.realm, is_system_group=True
+ )
+ do_change_stream_group_based_setting(
+ stream, "can_send_message_group", admins_group, acting_user=user_profile
)
usermessage = most_recent_usermessage(user_profile)
@@ -1204,7 +1208,7 @@ class TestMissedMessageEmailMessages(ZulipTestCase):
self.assertEqual(
message.content,
- "Error sending message to channel announce via message notification email reply:\nOnly organization administrators can send to this channel.",
+ "Error sending message to channel announce via message notification email reply:\nYou do not have permission to post in this channel.",
)
self.assertEqual(
message.sender,
diff --git a/zerver/tests/test_message_move_stream.py b/zerver/tests/test_message_move_stream.py
index a23709776e5..4b14d64d0d3 100644
--- a/zerver/tests/test_message_move_stream.py
+++ b/zerver/tests/test_message_move_stream.py
@@ -7,9 +7,8 @@ from zerver.actions.realm_settings import (
do_change_realm_permission_group_setting,
do_set_realm_property,
)
-from zerver.actions.streams import do_change_stream_post_policy
+from zerver.actions.streams import do_change_stream_group_based_setting
from zerver.actions.user_groups import check_add_user_group
-from zerver.actions.users import do_change_user_role
from zerver.lib.message import has_message_access
from zerver.lib.streams import check_update_all_streams_active_status
from zerver.lib.test_classes import ZulipTestCase, get_topic_messages
@@ -1029,9 +1028,9 @@ class MessageMoveStreamTest(ZulipTestCase):
cordelia, test_stream_1, test_stream_2, expect_error_message=None
)
- def test_move_message_to_stream_based_on_stream_post_policy(self) -> None:
+ def test_move_message_to_stream_based_on_can_send_message_group(self) -> None:
(user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
- "othello", "old_stream_1", "new_stream_1", "test"
+ "othello", "old_stream", "new_stream", "test"
)
realm = user_profile.realm
@@ -1046,18 +1045,27 @@ class MessageMoveStreamTest(ZulipTestCase):
acting_user=None,
)
- def check_move_message_to_stream(role: int, error_msg: str | None = None) -> None:
- do_change_user_role(user_profile, role, acting_user=None)
+ desdemona = self.example_user("desdemona")
+ iago = self.example_user("iago")
+ hamlet = self.example_user("hamlet")
+ othello = self.example_user("othello")
+ polonius = self.example_user("polonius")
- result = self.client_patch(
- "/json/messages/" + str(msg_id),
+ def check_move_message_to_stream(
+ user: UserProfile,
+ expect_fail: bool = False,
+ error_msg: str = "You do not have permission to post in this channel.",
+ ) -> None:
+ result = self.api_patch(
+ user,
+ "/api/v1/messages/" + str(msg_id),
{
"stream_id": new_stream.id,
"propagate_mode": "change_all",
},
)
- if error_msg is not None:
+ if expect_fail:
self.assert_json_error(result, error_msg)
messages = get_topic_messages(user_profile, old_stream, "test")
self.assert_length(messages, 3)
@@ -1070,62 +1078,62 @@ class MessageMoveStreamTest(ZulipTestCase):
messages = get_topic_messages(user_profile, new_stream, "test")
self.assert_length(messages, 4)
- # Check when stream_post_policy is STREAM_POST_POLICY_ADMINS.
- do_change_stream_post_policy(
- new_stream, Stream.STREAM_POST_POLICY_ADMINS, acting_user=user_profile
+ nobody_group = NamedUserGroup.objects.get(
+ name=SystemGroups.NOBODY, realm=realm, is_system_group=True
)
- error_msg = "Only organization administrators can send to this channel."
- check_move_message_to_stream(UserProfile.ROLE_MODERATOR, error_msg)
- check_move_message_to_stream(UserProfile.ROLE_REALM_ADMINISTRATOR)
+ do_change_stream_group_based_setting(new_stream, "can_send_message_group", nobody_group)
- (user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
- "othello", "old_stream_2", "new_stream_2", "test"
- )
+ check_move_message_to_stream(desdemona, expect_fail=True)
+ check_move_message_to_stream(iago, expect_fail=True)
- # Check when stream_post_policy is STREAM_POST_POLICY_MODERATORS.
- do_change_stream_post_policy(
- new_stream, Stream.STREAM_POST_POLICY_MODERATORS, acting_user=user_profile
+ owners_group = NamedUserGroup.objects.get(
+ name=SystemGroups.OWNERS, realm=realm, is_system_group=True
)
- error_msg = "Only organization administrators and moderators can send to this channel."
- check_move_message_to_stream(UserProfile.ROLE_MEMBER, error_msg)
- check_move_message_to_stream(UserProfile.ROLE_MODERATOR)
+ do_change_stream_group_based_setting(new_stream, "can_send_message_group", owners_group)
+
+ check_move_message_to_stream(iago, expect_fail=True)
+ check_move_message_to_stream(desdemona)
(user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
- "othello", "old_stream_3", "new_stream_3", "test"
+ "othello", "old_stream", "new_stream", "test"
)
- # Check when stream_post_policy is STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS.
- do_change_stream_post_policy(
- new_stream, Stream.STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS, acting_user=user_profile
+ hamletcharacters_group = NamedUserGroup.objects.get(name="hamletcharacters", realm=realm)
+ do_change_stream_group_based_setting(
+ new_stream, "can_send_message_group", hamletcharacters_group
)
- error_msg = "New members cannot send to this channel."
- do_set_realm_property(
- user_profile.realm, "waiting_period_threshold", 100000, acting_user=None
+ check_move_message_to_stream(desdemona, expect_fail=True)
+ check_move_message_to_stream(iago, expect_fail=True)
+ check_move_message_to_stream(hamlet)
+
+ (user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
+ "othello", "old_stream", "new_stream", "test"
)
- check_move_message_to_stream(UserProfile.ROLE_MEMBER, error_msg)
- do_set_realm_property(user_profile.realm, "waiting_period_threshold", 0, acting_user=None)
- check_move_message_to_stream(UserProfile.ROLE_MEMBER)
+ setting_group = self.create_or_update_anonymous_group_for_setting([othello], [owners_group])
+ do_change_stream_group_based_setting(new_stream, "can_send_message_group", setting_group)
+
+ check_move_message_to_stream(iago, expect_fail=True)
+ check_move_message_to_stream(hamlet, expect_fail=True)
+ check_move_message_to_stream(desdemona)
(user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
- "othello", "old_stream_4", "new_stream_4", "test"
+ "othello", "old_stream", "new_stream", "test"
)
+ check_move_message_to_stream(othello)
- # Check when stream_post_policy is STREAM_POST_POLICY_EVERYONE.
- # In this case also, guest is not allowed as we do not allow guest to move
- # messages between streams in any case, so stream_post_policy of new stream does
- # not matter.
- do_change_stream_post_policy(
- new_stream, Stream.STREAM_POST_POLICY_EVERYONE, acting_user=user_profile
+ (user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
+ "polonius", "old_stream", "new_stream", "test"
)
- do_set_realm_property(
- user_profile.realm, "waiting_period_threshold", 100000, acting_user=None
+ everyone_group = NamedUserGroup.objects.get(
+ name=SystemGroups.EVERYONE, realm=realm, is_system_group=True
)
+ do_change_stream_group_based_setting(new_stream, "can_send_message_group", everyone_group)
check_move_message_to_stream(
- UserProfile.ROLE_GUEST, "You don't have permission to move this message"
+ polonius, expect_fail=True, error_msg="You don't have permission to move this message"
)
- check_move_message_to_stream(UserProfile.ROLE_MEMBER)
+ check_move_message_to_stream(hamlet)
def test_move_message_to_stream_with_topic_editing_not_allowed(self) -> None:
(user_profile, old_stream, new_stream, msg_id, msg_id_later) = self.prepare_move_topics(
diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py
index b9382b1a733..bc06d054390 100644
--- a/zerver/tests/test_message_send.py
+++ b/zerver/tests/test_message_send.py
@@ -30,7 +30,7 @@ from zerver.actions.realm_settings import (
do_change_realm_permission_group_setting,
do_set_realm_property,
)
-from zerver.actions.streams import do_change_stream_post_policy, do_deactivate_stream
+from zerver.actions.streams import do_change_stream_group_based_setting, do_deactivate_stream
from zerver.actions.user_groups import add_subgroups_to_user_group, check_add_user_group
from zerver.actions.user_settings import do_change_user_setting
from zerver.actions.users import do_change_can_forge_sender, do_deactivate_user
@@ -246,286 +246,176 @@ class MessagePOSTTest(ZulipTestCase):
sent_message = self.get_last_message()
self.assertEqual(sent_message.content, content)
- def test_sending_message_as_stream_post_policy_admins(self) -> None:
- """
- Sending messages to streams which only the admins can post to.
- """
- admin_profile = self.example_user("iago")
- self.login_user(admin_profile)
+ def test_can_send_message_group_permission(self) -> None:
+ realm = get_realm("zulip")
- stream_name = "Verona"
- stream = get_stream(stream_name, admin_profile.realm)
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_ADMINS, acting_user=admin_profile
- )
+ desdemona = self.example_user("desdemona")
+ iago = self.example_user("iago")
+ hamlet = self.example_user("hamlet")
+ cordelia = self.example_user("cordelia")
+ othello = self.example_user("othello")
+ polonius = self.example_user("polonius")
- # Admins and their owned bots can send to STREAM_POST_POLICY_ADMINS streams
- self._send_and_verify_message(admin_profile, stream_name)
- admin_owned_bot = self.create_test_bot(
+ desdemona_owned_bot = self.create_test_bot(
short_name="whatever1",
full_name="whatever1",
- user_profile=admin_profile,
+ user_profile=desdemona,
)
- self._send_and_verify_message(admin_owned_bot, stream_name)
-
- non_admin_profile = self.example_user("hamlet")
- self.login_user(non_admin_profile)
-
- # Non admins and their owned bots cannot send to STREAM_POST_POLICY_ADMINS streams
- self._send_and_verify_message(
- non_admin_profile,
- stream_name,
- "Only organization administrators can send to this channel.",
- )
- non_admin_owned_bot = self.create_test_bot(
+ iago_owned_bot = self.create_test_bot(
short_name="whatever2",
full_name="whatever2",
- user_profile=non_admin_profile,
- )
- self._send_and_verify_message(
- non_admin_owned_bot,
- stream_name,
- "Only organization administrators can send to this channel.",
- )
-
- moderator_profile = self.example_user("shiva")
- self.login_user(moderator_profile)
-
- # Moderators and their owned bots cannot send to STREAM_POST_POLICY_ADMINS streams
- self._send_and_verify_message(
- moderator_profile,
- stream_name,
- "Only organization administrators can send to this channel.",
+ user_profile=iago,
)
- moderator_owned_bot = self.create_test_bot(
+ cordelia_owned_bot = self.create_test_bot(
short_name="whatever3",
full_name="whatever3",
- user_profile=moderator_profile,
+ user_profile=cordelia,
)
- self._send_and_verify_message(
- moderator_owned_bot,
- stream_name,
- "Only organization administrators can send to this channel.",
+ othello_owned_bot = self.create_test_bot(
+ short_name="whatever4",
+ full_name="whatever4",
+ user_profile=othello,
)
+ notification_bot = get_system_bot("[email protected]", realm.id)
- # Bots without owner (except cross realm bot) cannot send to announcement only streams
bot_without_owner = do_create_user(
password="",
- realm=non_admin_profile.realm,
+ realm=realm,
full_name="freebot",
bot_type=UserProfile.DEFAULT_BOT,
acting_user=None,
)
+
+ stream_name = "Verona"
+ stream = get_stream(stream_name, realm)
+
+ nobody_group = NamedUserGroup.objects.get(
+ name=SystemGroups.NOBODY, realm=realm, is_system_group=True
+ )
+ do_change_stream_group_based_setting(stream, "can_send_message_group", nobody_group)
+
self._send_and_verify_message(
- bot_without_owner,
- stream_name,
- "Only organization administrators can send to this channel.",
+ desdemona, stream_name, "You do not have permission to post in this channel."
+ )
+ self._send_and_verify_message(
+ desdemona_owned_bot, stream_name, "You do not have permission to post in this channel."
+ )
+ self._send_and_verify_message(
+ bot_without_owner, stream_name, "You do not have permission to post in this channel."
)
# Cross realm bots should be allowed
- notification_bot = get_system_bot("[email protected]", stream.realm_id)
internal_send_stream_message(
notification_bot, stream, "Test topic", "Test message by notification bot"
)
self.assertEqual(self.get_last_message().content, "Test message by notification bot")
- guest_profile = self.example_user("polonius")
- # Guests cannot send to non-STREAM_POST_POLICY_EVERYONE streams
- self._send_and_verify_message(
- guest_profile, stream_name, "Only organization administrators can send to this channel."
+ owners_group = NamedUserGroup.objects.get(
+ name=SystemGroups.OWNERS, realm=realm, is_system_group=True
)
+ do_change_stream_group_based_setting(stream, "can_send_message_group", owners_group)
- def test_sending_message_as_stream_post_policy_moderators(self) -> None:
- """
- Sending messages to streams which only the moderators can post to.
- """
- admin_profile = self.example_user("iago")
- self.login_user(admin_profile)
-
- stream_name = "Verona"
- stream = get_stream(stream_name, admin_profile.realm)
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_MODERATORS, acting_user=admin_profile
+ self._send_and_verify_message(
+ iago, stream_name, "You do not have permission to post in this channel."
)
-
- # Admins and their owned bots can send to STREAM_POST_POLICY_MODERATORS streams
- self._send_and_verify_message(admin_profile, stream_name)
- admin_owned_bot = self.create_test_bot(
- short_name="whatever1",
- full_name="whatever1",
- user_profile=admin_profile,
+ self._send_and_verify_message(
+ iago_owned_bot, stream_name, "You do not have permission to post in this channel."
+ )
+ self._send_and_verify_message(
+ bot_without_owner, stream_name, "You do not have permission to post in this channel."
)
- self._send_and_verify_message(admin_owned_bot, stream_name)
- moderator_profile = self.example_user("shiva")
- self.login_user(moderator_profile)
+ self._send_and_verify_message(desdemona, stream_name)
+ self._send_and_verify_message(desdemona_owned_bot, stream_name)
- # Moderators and their owned bots can send to STREAM_POST_POLICY_MODERATORS streams
- self._send_and_verify_message(moderator_profile, stream_name)
- moderator_owned_bot = self.create_test_bot(
- short_name="whatever2",
- full_name="whatever2",
- user_profile=moderator_profile,
+ # Cross realm bots should be allowed
+ internal_send_stream_message(
+ notification_bot, stream, "Test topic", "Test message by notification bot"
)
- self._send_and_verify_message(moderator_owned_bot, stream_name)
+ self.assertEqual(self.get_last_message().content, "Test message by notification bot")
- non_admin_profile = self.example_user("hamlet")
- self.login_user(non_admin_profile)
+ hamletcharacters_group = NamedUserGroup.objects.get(name="hamletcharacters", realm=realm)
+ do_change_stream_group_based_setting(
+ stream, "can_send_message_group", hamletcharacters_group
+ )
- # Members and their owned bots cannot send to STREAM_POST_POLICY_MODERATORS streams
self._send_and_verify_message(
- non_admin_profile,
- stream_name,
- "Only organization administrators and moderators can send to this channel.",
+ desdemona, stream_name, "You do not have permission to post in this channel."
)
- non_admin_owned_bot = self.create_test_bot(
- short_name="whatever3",
- full_name="whatever3",
- user_profile=non_admin_profile,
+ self._send_and_verify_message(
+ desdemona_owned_bot, stream_name, "You do not have permission to post in this channel."
)
self._send_and_verify_message(
- non_admin_owned_bot,
- stream_name,
- "Only organization administrators and moderators can send to this channel.",
+ iago, stream_name, "You do not have permission to post in this channel."
)
-
- # Bots without owner (except cross realm bot) cannot send to STREAM_POST_POLICY_MODERATORS streams.
- bot_without_owner = do_create_user(
- password="",
- realm=non_admin_profile.realm,
- full_name="freebot",
- bot_type=UserProfile.DEFAULT_BOT,
- acting_user=None,
+ self._send_and_verify_message(
+ iago_owned_bot, stream_name, "You do not have permission to post in this channel."
)
self._send_and_verify_message(
- bot_without_owner,
- stream_name,
- "Only organization administrators and moderators can send to this channel.",
+ bot_without_owner, stream_name, "You do not have permission to post in this channel."
)
- # System bots should be allowed
- notification_bot = get_system_bot("[email protected]", stream.realm_id)
+ self._send_and_verify_message(hamlet, stream_name)
+ self._send_and_verify_message(cordelia, stream_name)
+ self._send_and_verify_message(cordelia_owned_bot, stream_name)
+
+ # Cross realm bots should be allowed
internal_send_stream_message(
notification_bot, stream, "Test topic", "Test message by notification bot"
)
self.assertEqual(self.get_last_message().content, "Test message by notification bot")
- guest_profile = self.example_user("polonius")
- # Guests cannot send to non-STREAM_POST_POLICY_EVERYONE streams
+ setting_group = self.create_or_update_anonymous_group_for_setting([othello], [owners_group])
+ do_change_stream_group_based_setting(stream, "can_send_message_group", setting_group)
+
self._send_and_verify_message(
- guest_profile,
- stream_name,
- "Only organization administrators and moderators can send to this channel.",
+ iago, stream_name, "You do not have permission to post in this channel."
)
-
- def test_sending_message_as_stream_post_policy_restrict_new_members(self) -> None:
- """
- Sending messages to streams which new members cannot post to.
- """
- admin_profile = self.example_user("iago")
- self.login_user(admin_profile)
-
- do_set_realm_property(admin_profile.realm, "waiting_period_threshold", 10, acting_user=None)
- admin_profile.date_joined = timezone_now() - timedelta(days=9)
- admin_profile.save()
- self.assertTrue(admin_profile.is_provisional_member)
- self.assertTrue(admin_profile.is_realm_admin)
-
- stream_name = "Verona"
- stream = get_stream(stream_name, admin_profile.realm)
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS, acting_user=admin_profile
+ self._send_and_verify_message(
+ iago_owned_bot, stream_name, "You do not have permission to post in this channel."
)
-
- # Admins and their owned bots can send to STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS streams,
- # even if the admin is a new user
- self._send_and_verify_message(admin_profile, stream_name)
- admin_owned_bot = self.create_test_bot(
- short_name="whatever1",
- full_name="whatever1",
- user_profile=admin_profile,
+ self._send_and_verify_message(
+ hamlet, stream_name, "You do not have permission to post in this channel."
)
- self._send_and_verify_message(admin_owned_bot, stream_name)
-
- non_admin_profile = self.example_user("hamlet")
- self.login_user(non_admin_profile)
-
- non_admin_profile.date_joined = timezone_now() - timedelta(days=9)
- non_admin_profile.save()
- self.assertTrue(non_admin_profile.is_provisional_member)
- self.assertFalse(non_admin_profile.is_realm_admin)
-
- # Non admins and their owned bots can send to STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS streams,
- # if the user is not a new member
self._send_and_verify_message(
- non_admin_profile, stream_name, "New members cannot send to this channel."
+ cordelia, stream_name, "You do not have permission to post in this channel."
)
- non_admin_owned_bot = self.create_test_bot(
- short_name="whatever2",
- full_name="whatever2",
- user_profile=non_admin_profile,
+ self._send_and_verify_message(
+ cordelia_owned_bot, stream_name, "You do not have permission to post in this channel."
)
self._send_and_verify_message(
- non_admin_owned_bot, stream_name, "New members cannot send to this channel."
+ bot_without_owner, stream_name, "You do not have permission to post in this channel."
)
- non_admin_profile.date_joined = timezone_now() - timedelta(days=11)
- non_admin_profile.save()
- self.assertFalse(non_admin_profile.is_provisional_member)
+ self._send_and_verify_message(desdemona, stream_name)
+ self._send_and_verify_message(desdemona_owned_bot, stream_name)
+ self._send_and_verify_message(othello, stream_name)
+ self._send_and_verify_message(othello_owned_bot, stream_name)
- self._send_and_verify_message(non_admin_profile, stream_name)
- # We again set bot owner here, as date_joined of non_admin_profile is changed.
- non_admin_owned_bot.bot_owner = non_admin_profile
- non_admin_owned_bot.save()
- self._send_and_verify_message(non_admin_owned_bot, stream_name)
-
- # Bots without owner (except cross realm bot) cannot send to STREAM_POST_POLICY_ADMINS_ONLY and
- # STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS streams
- bot_without_owner = do_create_user(
- password="",
- realm=non_admin_profile.realm,
- full_name="freebot",
- bot_type=UserProfile.DEFAULT_BOT,
- acting_user=None,
- )
- self._send_and_verify_message(
- bot_without_owner, stream_name, "New members cannot send to this channel."
+ # Cross realm bots should be allowed
+ internal_send_stream_message(
+ notification_bot, stream, "Test topic", "Test message by notification bot"
)
+ self.assertEqual(self.get_last_message().content, "Test message by notification bot")
- moderator_profile = self.example_user("shiva")
- moderator_profile.date_joined = timezone_now() - timedelta(days=9)
- moderator_profile.save()
- self.assertTrue(moderator_profile.is_moderator)
- self.assertFalse(moderator_profile.is_provisional_member)
-
- # Moderators and their owned bots can send to STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS
- # streams, even if the moderator is a new user
- self._send_and_verify_message(moderator_profile, stream_name)
- moderator_owned_bot = self.create_test_bot(
- short_name="whatever3",
- full_name="whatever3",
- user_profile=moderator_profile,
+ everyone_group = NamedUserGroup.objects.get(
+ name=SystemGroups.EVERYONE, realm=realm, is_system_group=True
)
- moderator_owned_bot.date_joined = timezone_now() - timedelta(days=11)
- moderator_owned_bot.save()
- self._send_and_verify_message(moderator_owned_bot, stream_name)
+ do_change_stream_group_based_setting(stream, "can_send_message_group", everyone_group)
+ self._send_and_verify_message(othello, stream_name)
+ self._send_and_verify_message(othello_owned_bot, stream_name)
+ self._send_and_verify_message(iago, stream_name)
+ self._send_and_verify_message(iago_owned_bot, stream_name)
+ self._send_and_verify_message(polonius, stream_name)
+ self._send_and_verify_message(bot_without_owner, stream_name)
- # System bots should be allowed
- notification_bot = get_system_bot("[email protected]", stream.realm_id)
+ # Cross realm bots should be allowed
internal_send_stream_message(
notification_bot, stream, "Test topic", "Test message by notification bot"
)
self.assertEqual(self.get_last_message().content, "Test message by notification bot")
- guest_profile = self.example_user("polonius")
- # Guests cannot send to non-STREAM_POST_POLICY_EVERYONE streams
- self._send_and_verify_message(
- guest_profile, stream_name, "Guests cannot send to this channel."
- )
-
def test_api_message_with_default_to(self) -> None:
"""
Sending messages without a to field should be sent to the default
@@ -1737,6 +1627,24 @@ class StreamMessagesTest(ZulipTestCase):
body="@**all**",
)
+ # Query count increases if can_send_message_group setting is
+ # set to something other than "Everyone" group.
+ stream = get_stream(stream_name, realm)
+ members_group = NamedUserGroup.objects.get(
+ name=SystemGroups.MEMBERS, realm=realm, is_system_group=True
+ )
+ do_change_stream_group_based_setting(stream, "can_send_message_group", members_group)
+ flush_per_request_caches()
+
+ with self.assert_database_query_count(17):
+ check_send_stream_message(
+ sender=sender,
+ client=sending_client,
+ stream_name=stream_name,
+ topic_name="topic 2",
+ body="@**all**",
+ )
+
def test_stream_message_dict(self) -> None:
user_profile = self.example_user("iago")
self.subscribe(user_profile, "Denmark")
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index 0709b6e284e..8506ab1af24 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -38,7 +38,6 @@ from zerver.actions.streams import (
deactivated_streams_by_old_name,
do_change_stream_group_based_setting,
do_change_stream_permission,
- do_change_stream_post_policy,
do_deactivate_stream,
do_unarchive_stream,
)
@@ -5248,53 +5247,39 @@ class SubscriptionAPITest(ZulipTestCase):
self.assertEqual(add_peer_event["event"]["op"], "peer_add")
self.assertEqual(add_peer_event["event"]["user_ids"], [self.example_user("iago").id])
- def test_subscribe_to_stream_post_policy_admins_stream(self) -> None:
- """
- Members can subscribe to streams where only admins can post
- """
- member = self.example_user("AARON")
- stream = self.make_stream("stream1")
- do_change_stream_post_policy(stream, Stream.STREAM_POST_POLICY_ADMINS, acting_user=member)
- result = self.common_subscribe_to_streams(member, ["stream1"])
- json = self.assert_json_success(result)
- self.assertEqual(json["subscribed"], {str(member.id): ["stream1"]})
- self.assertEqual(json["already_subscribed"], {})
-
- def test_subscribe_to_stream_post_policy_restrict_new_members_stream(self) -> None:
- """
- New members can subscribe to streams where they cannot post
- """
- new_member_email = self.nonreg_email("test")
- self.register(new_member_email, "test")
- new_member = self.nonreg_user("test")
-
- do_set_realm_property(new_member.realm, "waiting_period_threshold", 10, acting_user=None)
- self.assertTrue(new_member.is_provisional_member)
+ def test_subscribing_to_stream_without_permission_to_post(self) -> None:
+ stream = self.make_stream("stream_name1")
+ realm = get_realm("zulip")
- stream = self.make_stream("stream1")
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_RESTRICT_NEW_MEMBERS, acting_user=new_member
+ iago = self.example_user("iago")
+ admins_group = NamedUserGroup.objects.get(
+ name=SystemGroups.ADMINISTRATORS, realm=realm, is_system_group=True
+ )
+ do_change_stream_group_based_setting(
+ stream, "can_send_message_group", admins_group, acting_user=iago
)
- result = self.common_subscribe_to_streams(new_member, ["stream1"])
+
+ # Members can subscribe even when only admins can post.
+ member = self.example_user("hamlet")
+ result = self.common_subscribe_to_streams(member, ["stream_name1"])
json = self.assert_json_success(result)
- self.assertEqual(json["subscribed"], {str(new_member.id): ["stream1"]})
+ self.assertEqual(json["subscribed"], {str(member.id): ["stream_name1"]})
self.assertEqual(json["already_subscribed"], {})
- def test_subscribe_to_stream_post_policy_moderators_stream(self) -> None:
- """
- Members can subscribe to streams where only admins and moderators can post
- """
- member = self.example_user("AARON")
- stream = self.make_stream("stream1")
- # Make sure that we are testing this with full member which is just below the moderator
- # in the role hierarchy.
- self.assertFalse(member.is_provisional_member)
- do_change_stream_post_policy(
- stream, Stream.STREAM_POST_POLICY_MODERATORS, acting_user=member
+ moderators_group = NamedUserGroup.objects.get(
+ name=SystemGroups.MODERATORS, realm=realm, is_system_group=True
)
- result = self.common_subscribe_to_streams(member, ["stream1"])
+ setting_group = self.create_or_update_anonymous_group_for_setting(
+ [self.example_user("cordelia")], [moderators_group]
+ )
+ do_change_stream_group_based_setting(
+ stream, "can_send_message_group", setting_group, acting_user=iago
+ )
+
+ member = self.example_user("othello")
+ result = self.common_subscribe_to_streams(member, ["stream_name1"])
json = self.assert_json_success(result)
- self.assertEqual(json["subscribed"], {str(member.id): ["stream1"]})
+ self.assertEqual(json["subscribed"], {str(member.id): ["stream_name1"]})
self.assertEqual(json["already_subscribed"], {})
def test_guest_user_subscribe(self) -> None:
diff --git a/zerver/views/typing.py b/zerver/views/typing.py
index 2285206626b..ff1b54aa3c5 100644
--- a/zerver/views/typing.py
+++ b/zerver/views/typing.py
@@ -7,7 +7,7 @@ from pydantic import Json
from zerver.actions.typing import check_send_typing_notification, do_send_stream_typing_notification
from zerver.lib.exceptions import JsonableError
from zerver.lib.response import json_success
-from zerver.lib.streams import access_stream_by_id, access_stream_for_send_message
+from zerver.lib.streams import access_stream_by_id_for_message, access_stream_for_send_message
from zerver.lib.typed_endpoint import ApiParamConfig, OptionalTopic, typed_endpoint
from zerver.models import UserProfile
@@ -42,7 +42,7 @@ def send_notification_backend(
# Verify that the user has access to the stream and has
# permission to send messages to it.
- stream = access_stream_by_id(user_profile, stream_id)[0]
+ stream = access_stream_by_id_for_message(user_profile, stream_id)[0]
access_stream_for_send_message(user_profile, stream, forwarder_user_profile=None)
do_send_stream_typing_notification(user_profile, operator, stream, topic)
else:
diff --git a/zilencer/management/commands/populate_db.py b/zilencer/management/commands/populate_db.py
index 3248f903c23..c8f27f33b03 100644
--- a/zilencer/management/commands/populate_db.py
+++ b/zilencer/management/commands/populate_db.py
@@ -70,6 +70,7 @@ from zerver.models import (
)
from zerver.models.alert_words import flush_alert_word
from zerver.models.clients import get_client
+from zerver.models.groups import NamedUserGroup, SystemGroups
from zerver.models.onboarding_steps import OnboardingStep
from zerver.models.realm_audit_logs import AuditLogEventType
from zerver.models.realms import WildcardMentionPolicyEnum, get_realm
@@ -1024,6 +1025,9 @@ class Command(ZulipBaseCommand):
# to imitate emoji insertions in stream names
raw_emojis = ["😎", "😂", "🐱‍👤"]
+ admins_system_group = NamedUserGroup.objects.get(
+ name=SystemGroups.ADMINISTRATORS, realm=zulip_realm, is_system_group=True
+ )
zulip_stream_dict: dict[str, dict[str, Any]] = {
"devel": {"description": "For developing"},
# ビデオゲーム - VideoGames (japanese)
@@ -1033,7 +1037,7 @@ class Command(ZulipBaseCommand):
},
"announce": {
"description": "For announcements",
- "stream_post_policy": Stream.STREAM_POST_POLICY_ADMINS,
+ "can_send_message_group": admins_system_group,
},
"design": {"description": "For design", "creator": hamlet},
"support": {"description": "For support"},