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.

narrow: Do early return for inaccessible channels.

Aman Agrawaldf7e1d51ed05
diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py
index b09fa520ad7..9f8d0007e4f 100644
--- a/zerver/lib/narrow.py
+++ b/zerver/lib/narrow.py
@@ -44,6 +44,7 @@ from zerver.lib.narrow_predicate import channel_operators, channels_operators
from zerver.lib.recipient_users import recipient_for_user_profiles
from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection
from zerver.lib.streams import (
+ access_stream_common,
can_access_stream_history_by_id,
can_access_stream_history_by_name,
get_public_streams_queryset,
@@ -1511,6 +1512,20 @@ def fetch_messages(
num_after: int,
client_requested_message_ids: list[int] | None = None,
) -> FetchedMessages:
+ if access_narrow(user_profile, narrow, is_web_public_query, realm) is False:
+ # If user is requesting messages from a narrow they don't have
+ # access to, do an early return.
+ return FetchedMessages(
+ rows=[],
+ found_anchor=False,
+ found_oldest=True,
+ found_newest=True,
+ history_limited=False,
+ anchor=LARGER_THAN_MAX_MESSAGE_ID,
+ include_history=False,
+ is_search=False,
+ )
+
include_history = ok_to_include_history(narrow, user_profile, is_web_public_query)
if include_history:
# The initial query in this case doesn't use `zerver_usermessage`,
@@ -1664,3 +1679,65 @@ def fetch_messages(
include_history=include_history,
is_search=is_search,
)
+
+
+def access_narrow(
+ maybe_user_profile: UserProfile | None,
+ narrow: list[NarrowParameter] | None,
+ is_web_public_query: bool,
+ realm: Realm,
+) -> bool | None:
+ """
+ We do an early return if the user doesn't have access to the
+ channel present in the narrow.
+
+ @returns None if we can't determine access here.
+ """
+
+ if (is_web_public_query is True) or (maybe_user_profile is None):
+ # Not handled here since we already have channel access
+ # checks later which will return with status code.
+ return None
+
+ # We only expect one channel term.
+ channel_requested_by_user: str | int | None = None
+ if narrow is not None:
+ for term in narrow:
+ if term.operator in channel_operators:
+ if term.negated:
+ # We don't handle negated channel terms here.
+ return None
+ if channel_requested_by_user is not None:
+ # If there are multiple channel terms, there will
+ # be no messages since we apply `AND` on them.
+ return False
+ channel_requested_by_user = term.operand
+
+ if channel_requested_by_user is None:
+ return None
+
+ # Import here to avoid circular imports
+ from zerver.models.streams import get_realm_stream, get_stream_by_id_in_realm
+
+ # Check if channel exists.
+ try:
+ if isinstance(channel_requested_by_user, str):
+ channel = get_realm_stream(channel_requested_by_user, realm.id)
+ else:
+ channel = get_stream_by_id_in_realm(channel_requested_by_user, realm)
+ except Stream.DoesNotExist:
+ # We don't want to duplicate validation error messages here, so
+ # just return `None`.
+ return None
+
+ try:
+ access_stream_common(
+ maybe_user_profile,
+ channel,
+ error="",
+ require_content_access=True,
+ )
+ return True
+ except JsonableError:
+ # User doesn't have access to this existing stream
+ return False
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index 038a453b4b2..f17b3daf455 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -4632,7 +4632,7 @@ class GetOldMessagesTest(ZulipTestCase):
# Narrow conditions should be respected when passing `anchor_date`.
scotland_channel_message_id = self.send_stream_message(sender, "Scotland")
Message.objects.filter(id=scotland_channel_message_id).update(date_sent=base_time)
- with self.assert_database_query_count(14):
+ with self.assert_database_query_count(16):
result = self.get_and_check_messages(
{
**get_and_check_messages_options,
@@ -5490,6 +5490,70 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.
# Incoming DMs show the recipient_id that outgoing DMs would.
self.assertEqual(result["messages"][1]["recipient_id"], othello.recipient_id)
+ def test_early_return_for_no_access_private_channel(self) -> None:
+ """Test that we do an early return when trying to access messages
+ in a private stream the user doesn't have access to.
+ """
+ hamlet = self.example_user("hamlet")
+ self.make_stream("private_stream", invite_only=True)
+ self.login_user(hamlet)
+
+ # Check that we do an early return.
+ with mock.patch(
+ "zerver.lib.narrow.get_base_query_for_search",
+ ) as mocked_get_base_query_for_search:
+ narrow = [["stream", "private_stream"]]
+ result = self.get_and_check_messages(
+ dict(
+ narrow=orjson.dumps(narrow).decode(),
+ anchor=LARGER_THAN_MAX_MESSAGE_ID,
+ ),
+ expected_status=200,
+ )
+ mocked_get_base_query_for_search.assert_not_called()
+ self.assert_length(result["messages"], 0)
+
+ def test_negated_channel_does_not_early_return(self) -> None:
+ """Test that negated channel terms don't trigger early return in access_narrow."""
+ hamlet = self.example_user("hamlet")
+ self.login_user(hamlet)
+
+ # Negated channel terms should not trigger the early return optimization.
+ # The query should proceed normally and apply the negation filter.
+ narrow = [{"operator": "channel", "operand": "Verona", "negated": True}]
+ result = self.get_and_check_messages(
+ dict(
+ narrow=orjson.dumps(narrow).decode(),
+ anchor=LARGER_THAN_MAX_MESSAGE_ID,
+ ),
+ expected_status=200,
+ )
+ self.assertGreater(len(result["messages"]), 0)
+
+ def test_multiple_channel_terms_early_return(self) -> None:
+ """Test that multiple channel terms trigger early return with no messages."""
+ hamlet = self.example_user("hamlet")
+ self.login_user(hamlet)
+
+ # Multiple channel terms with AND logic will never match any messages,
+ # so we should get an early return with no messages.
+ with mock.patch(
+ "zerver.lib.narrow.get_base_query_for_search",
+ ) as mocked_get_base_query_for_search:
+ narrow = [
+ {"operator": "channel", "operand": "Verona"},
+ {"operator": "channel", "operand": "Scotland"},
+ ]
+ result = self.get_and_check_messages(
+ dict(
+ narrow=orjson.dumps(narrow).decode(),
+ anchor=LARGER_THAN_MAX_MESSAGE_ID,
+ ),
+ expected_status=200,
+ )
+ mocked_get_base_query_for_search.assert_not_called()
+ self.assert_length(result["messages"], 0)
+
class MessageHasKeywordsTest(ZulipTestCase):
"""Test for keywords like has_link, has_image, has_attachment."""