Commit Graph

6811 Commits

Author SHA1 Message Date
Anders Kaseorg d1c05467ec push_notifications: Fix RemoteZulipServer annotation to work at runtime.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-10-20 00:48:55 -07:00
Alex Vandiver c0b557fb2e push_notifications: Move zilencer import inside ZILENCER_ENABLED check. 2021-10-20 06:16:10 +00:00
Alex Vandiver 111ee64e36 push_notifications: Pass down the remote server and user-id for logs.
This makes logging more consistent between FCM and APNs codepaths, and
makes clear which user-ids are for local users, and which are opaque
integers namespaced from some remote zulip server.
2021-10-19 22:04:24 -07:00
Alex Vandiver 5bcd3c01cb push_notifications: Add log line with user-id, UUID, and devices.
Being able to determine how many distinct users are getting push
notifications per remote host is useful, as is the distribution of
device counts.  This parallels the log line in
handle_push_notification for push notifications from local realms,
handled via the event queue.
2021-10-19 22:04:24 -07:00
rht bb8504d925 lint: Fix typos found by codespell. 2021-10-19 16:51:13 -07:00
Eeshan Garg b325a4f1be realm: Rename plan type constants to be more descriptive.
It is confusing to have the plan type constants not be namespaced
by the thing they represent. We already have a namespacing
convention in place for constants, so we should use it for
Realm.plan_type as well.
2021-10-19 12:20:39 -07:00
Alex Vandiver b02754adec html_diff: Handle empty differences between empty strings.
`rendered_content` in historical messages may be empty; examining the
history of them may thus require diff'ing two empty strings, which
itself produces an empty string.

Use `lxml.html.fragment_fromstring` to be able to successfully parse
these, rather than 500.

Part of #19559.
2021-10-18 18:27:40 -07:00
Mateusz Mandera f5a65846a8 scim: Override django-scim2 logic of exception handling in views.
As detailed in the comments, the default behavior is undesirable for us
because we can't really predict all possibilities of exceptions that may
be raised - and thus putting str(e) in the http response is potentially
insecure as it may leak some unexpected sensitive information that was
in the exception.

As a hypothetical example - KeyError resulting from some buggy
some_dict[secret_string] call would leak information. Though of course
we aim to never write code like that.
2021-10-17 21:33:03 -07:00
Vishnu KS aff52722a7 billing: Add PLUS as a plan_type to Realm. 2021-10-15 17:27:50 -07:00
Alya Abbott 60535adfc7 onboarding: Update Welcome Bot.
The most important thing is linking to the new user guide.
2021-10-15 12:59:20 -07:00
Anders Kaseorg 3bd3173b1f avatar: Remove ?x=x kludge.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-10-14 12:47:43 -07:00
Anders Kaseorg 58771d6e66 avatar: Use append_url_query_string.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-10-14 12:47:43 -07:00
Anders Kaseorg f42e191776 url_encoding: Use proper parsing for query string appending.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-10-14 12:47:43 -07:00
Mateusz Mandera 73a6f2a1a7 auth: Add support for using SCIM for account management. 2021-10-14 12:29:10 -07:00
Mateusz Mandera 7c0995b14b actions: Support acting_user=None in check_change_full_name.
do_change_full_name supports it already, so this is a trivial change.
2021-10-14 12:28:35 -07:00
Anders Kaseorg 1e5157b66c user_groups: Add a recursive group membership model.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-10-13 10:08:06 -07:00
Sahil Batra 6ac9386a29 models: Add related_name to UserGroup and UserGroupMembership fields.
This commit adds related_name parameter to UserGroup.direct_members
such that we can use direct_groups instead of the default
usergroupmembership_set for getting all the groups of which the
user is direct member.

This commit also sets related_name of UserGroupMembership.user_group
and UserGroupMembership.user_profile to "+" which means that we will
not be having backward relations for these. This change is correct
since we would need to use the recursive queries to get all the
groups of a user and all the members of a group after we add the
subgroups concept in next commit. This leads to us using direct_members
field of UserGroup instead of usergroupmembership_set in mention code,
but this will soon be replaced with the recursive query function to
include subgroup's members as well.

Extracted this commit from #19866.

Authored-by : Anders Kaseorg <anders@zulip.com>
2021-10-13 10:08:06 -07:00
Sahil Batra 6f31b959ac user_groups: Fix return type of get_user_group_direct_members.
This commit fixes return type of get_user_group_direct_members
function which returns a list of user profile ids and not UserProfile
objects.
2021-10-13 16:57:04 +05:30
Sahil Batra b65aadae4b user_groups: Make get_user_group_direct_members query efficient.
This commit makes the query in get_user_group_direct_members
efficient by directly fetching user-profile ids instead of
first fetching user profile object and then id.
2021-10-13 16:56:44 +05:30
Sahil Batra 2d39b14a38 user_groups: Rename members field of UserGroup to direct_members.
This commit renames members field of UserGroup to direct_members
for better readability because in the new permissions model, a
user group can be a sub-group of another group and thus technically
members of sub-group will also be members of that group.
This is a prep commit for new permissions model.

Extracted this commit from #19866.

Co-authored-by: Anders Kaseorg <anders@zulip.com>
2021-10-12 13:57:53 -07:00
Sahil Batra e47662aa19 user_groups: Rename get_memberships_of_users.
This is a prep commit for new permissions model in
which a user group would be able to have a subgroup.

This commit renames get_memberships_of_users to
get_direct_memberships_of_users to specify that
the function is used only to fetch the direct
memberships and not memberships of subgroups of
the direct group.

Extracted this commit from #19866.

Co-authored-by: Anders Kaseorg <anders@zulip.com>
2021-10-12 13:57:47 -07:00
Sahil Batra 07e2ecf221 user_groups: Rename get_user_groups to get_direct_user_groups.
This is a prep commit for new permissions model in which a user
group would be able to have a subgroup.

This commit renames get_user_groups to get_direct_user_groups
to specify that the function is used only to fetch the direct
groups that user is part of and not subgroups of the direct
group.

Extracted this commit from #19866.

Co-authored-by: Anders Kaseorg <anders@zulip.com>
2021-10-12 13:57:32 -07:00
Sahil Batra 82af2d3db5 user_groups: Rename get_user_group_members to get_user_group_direct_members.
This is a prep commit for new permissions model in which a user group would
be able to have a subgroup.

This commit renames get_user_group_members to get_user_group_direct_members
to specify that the function is used only to fetch direct members of group
and excludes the subgroup's members.

Extracted this commit from #19866.

Co-authored-by: Anders Kaseorg <anders@zulip.com>
2021-10-12 13:57:26 -07:00
Dinesh 0b68f264c6 apply_event: Do not include new user settings in the top level.
From 430c5cb, in `fetch_initial_state_data`,
we only include legacy settings in the top level of
`state` and the newer ones are stored in `state['user_settings']`.
That should've had a corresponding change in apply_event().

Also, fixed a test related to this logic.
2021-10-07 16:39:51 -07:00
Eeshan Garg 29b354346b update_realm: Allow demo orgs to be converted to regular orgs.
This commit adds support to the `PATCH /realm` endpoint for
converting a demo organization to a regular organization.

This is a part of #19523.
2021-10-07 14:43:03 -07:00
Eeshan Garg f25230c7d4 analytics/support: Add ability to edit realm org type. 2021-10-07 14:08:11 -07:00
Alya Abbott 8045355eee user docs: Document public vs. private stream creation permissions. 2021-10-06 17:33:19 -07:00
Aman Agrawal 3b29c61409 auth: Add login buttons for web public access.
For users who are not logged in and for those who don't have
'prefers_web_public_view' set in session, we redirect them
to the default login page where they can choose to login
as spectator or authenticated user.
2021-10-05 16:30:40 -07:00
Sahil Batra ab0d852fd5 register: Add can_create_web_public_streams to register response. 2021-10-05 10:10:32 -07:00
Sahil Batra 2c2c19c4d4 streams: Restrict creating web public streams based on new setting.
This commit restricts creating web public streams based on the
recently added create_web_public_stream_policy setting.
2021-10-05 09:56:00 -07:00
Sahil Batra 3916181770 models: Add can_create_web_public_streams helper.
This commit adds can_create_web_public_streams helper
in models.py which will be used to validate whether
user is allowed to create a web-public stream or not.

This commit also adds the checks for Realm.POLICY_OWNERS_ONLY
in check_has_permission_policies.
2021-10-05 09:48:50 -07:00
Sahil Batra a63385f47f tests: Check all cases in check_has_permission_policies.
This commit adds tests for POLICY_EVERYONE and POLICY_NOBODY
in check_has_permission_policies test. The original code
used these values but these were not covered in test.
2021-10-05 09:12:56 -07:00
Sahil Batra c07b8e9b44 tests: Validate owner users also in check_has_permission_policies.
We should validate owner user also for all policy values. This is
important when we will add tests for POLICY_NOBODY in next commit.
2021-10-05 09:12:56 -07:00
Sahil Batra eedd832ca9 events: Fix updating user email on changing email_address_visibility.
When email_address_visibility is changed and either the old value
or the updated value is EMAIL_ADDRESS_VISIBILITY_EVERYONE then
email field of all users is updated and we also send the corresponding
event to clients. But apply_event code did not update the data on
receiving the event, so this commit fixes the code to correctly
handle the event in apply_event.

(We also use this event when just changing a user's email address).

This commit also adds the tests and openapi schema for the event.
2021-10-04 17:24:31 -07:00
Eeshan Garg c4aeb159c4 topics: Fix translation issue with moved topic notifications.
Since the calls to the translation function `_()` are made outside
of the `send_message_moved_breadcrumbs` function, these strings are
translated outside of the `with override_language` block, leading to
translated strings even when we don't intend them to be translated.

We now use gettext_lazy with appropriate testing to avoid this.
2021-10-04 16:20:16 -07:00
Alex Vandiver db934be064 CVE-2021-41115: Use re2 for user-supplied linkifier patterns.
Zulip attempts to validate that the regular expressions that admins
enter for linkifiers are well-formatted, and only contain a specific
subset of regex grammar.  The process of checking these
properties (via a regex!) can cause denial-of-service via
backtracking.

Furthermore, this validation itself does not prevent the creation of
linkifiers which themselves cause denial-of-service when they are
executed.  As the validator accepts literally anything inside of a
`(?P<word>...)` block, any quadratic backtracking expression can be
hidden therein.

Switch user-provided linkifier patterns to be matched in the Markdown
processor by the `re2` library, which is guaranteed constant-time.
This somewhat limits the possible features of the regular
expression (notably, look-head and -behind, and back-references);
however, these features had never been advertised as working in the
context of linkifiers.

A migration removes any existing linkifiers which would not function
under re2, after printing them for posterity during the upgrade; they
are unlikely to be common, and are impossible to fix automatically.

The denial-of-service in the linkifier validator was discovered by
@erik-krogh and @yoff, as GHSL-2021-118.
2021-10-04 21:26:24 +00:00
Pradyumna Sinha 18b36e5b8c markdown/tabbed_sections: Raise exception for missing tab name.
This fixes the issue  where 'None' would appear in the rendered
html in case of a missing tab display_name. Now,
'test-help-documentation' will fail in case of any tab display_name
being missing.

In case of a tab_section with no tabs, currently a single tab with
the name 'null_tab' gets added. Added the display name 'None' for
'null_tab', to keep in line with the existing behaviour.

Fixes #19822
2021-10-01 16:25:17 -07:00
Pradyumna Sinha 78692e9c14 markdown/tabbed_sections: Don't set tab label as 'None' in case of no tabs. 2021-10-01 16:22:11 -07:00
Pradyumna Sinha fe5de4a128 markdown/tabbed_sections: Rename TAB_DISPLAY_NAMES to TAB_SECTION_LABELS. 2021-10-01 16:22:11 -07:00
Shlok Patel 1e18d36328 realm: Change default permissions for education organizations.
This makes our onboarding guide for education organizations much
simpler, since new organizations will start with these settings
correctly configured.

Fixes #19682
2021-10-01 15:33:33 -07:00
Ganesh Pawar fa928d5cd1 streams: Split setting for stream creation policy.
Users wanted a feature where they could specify
which users can create public streams and which users can
create private streams.

This splits stream creation code into two parts,
public and private stream creation.

Fixes #17009.
2021-10-01 10:26:42 -07:00
sahil839 909a3cde76 realm: Replace allow_message_deleting with delete_own_message_policy.
This commit replaces 'allow_message_deleting' boolean setting
with an integer setting 'delete_own_message_policy'. We have a
separate dropdown now for deciding which user-roles can delete
messages sent by themselves and the time-limit setting droddown
is different.

This new setting has two options - everyone and admins only. Other
options including moderators will be added further.

We also remove the "Never" option from the original time-limit
dropdown, as admins are always allowed to delete message. This
never option resembled the case of only admins being allowed to
delete but this state is now resembled by setting the dropdown
to "admins only" and we also disable the time-limit dropdown in
this case as admins are allowed to delete irrespective of limit.

Note, this setting is only for deleting messages sent by the
deleting user themselves, and only admins are allowed to delete
messages sent by others as before.
2021-09-30 14:59:31 -07:00
sahil839 b13bfa09c5 message: Make zero invalid value for message_content_delete_limit_seconds.
We make zero invalid value for message_content_delete_limit_seconds and
for handling the case of "Allow to delete message any time", the API-level
value of message_content_delete_limit_seconds is "anytime" and "None"
as the DB-level value. We also use these values for message retention
setting, so it helps maintain consistency.
2021-09-30 14:45:39 -07:00
Mateusz Mandera 0af7c84c99 push_notifs: Log the number of devices notification was sent to. 2021-09-29 15:50:06 -07:00
Sahil Batra d1732fb9da settings: Remove realm-level default of enable_login_emails setting.
This commit does not remove the 'enable_login_emails' field from
RealmUserDefault table but it is just not used and cannot be
changed from UI or API similar to 'enable_marketing_emails' setting.
2021-09-28 12:41:09 -07:00
Aman Agrawal ef84224eed message_edit: Allow spectators to access raw message content.
We allow spectators to fetch the raw / original content of a
message which is used by the spectator to "View source" of
the message.
2021-09-28 10:07:36 -07:00
Tim Abbott e556481ba0 streams: Remove duplicates of get_web_public_streams_queryset.
This is a somewhat subtle function, that deserves a few comments
explaining subtle details of its logic, and there's no good reason to
have multiple copies of that logic that are slightly inconsistent.

Because the main changes here are just checking for invariant
failures, the behavioral change here should be limited to ensuring
deactivated streams are not considered available even if they were
tagged as web public streams before deactivation.
2021-09-28 10:07:36 -07:00
Tim Abbott 272e81988b tornado: Make process_notification hack avoid import loops.
This fixes a problem where we could not import zerver.lib.streams from
zerver.lib.message, which would otherwise be reasonable, because the
former implicitly imported many modules due to this issue.
2021-09-28 10:07:36 -07:00
Anders Kaseorg 0f7d0a23c9 Revert "validator: Add generic check_or."
This reverts commit cd93d0967f.

This check_or is redundant with check_union; it gives a misleading
error message for the non-matching case; and it has no type safety.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-09-28 09:28:56 -07:00
seiwailai cd93d0967f validator: Add generic check_or.
Added generic check_or function and tests.
Fixes part of #17914.

Co-authored-by: Gaurav Pandey <gauravguitarrocks@gmail.com>
2021-09-27 17:30:26 -07:00
Kevin Scott 09851ff290 markdown: Document built-in preprocessor priorities for convenience.
Fixes #19810
2021-09-27 10:42:09 -07:00
Eeshan Garg bf64cb2d1c topics: Fix translation issue with resolve topic notifications.
In maybe_send_resolve_topic_notifications, since the calls to the
translation function `_()` are made outside of the `override_language`
block, the strings are not translated correctly.

This commit refactors the function to make sure that the translation
happens in the right block of code.

Fixes #19730.
2021-09-23 17:21:33 -07:00
Tim Abbott 417c32629d outgoing webhooks: Fix inconsistencies with Slack's API.
Apparently, our slack compatible outgoing webhook format didn't
exactly match Slack, especially in the types used for values.  Fix
this by using a much more consistent format, where we preserve their
pattern of prefixing IDs with letters.

This fixes a bug where Zulip's team_id could be the empty string,
which tripped up using GitLab's slash commands with Zulip.

Fixes #19588.
2021-09-23 11:19:20 -07:00
Sahil Batra c233ee9935 settings: Migrate twenty_four_hour_time setting to RealmUserDefault.
This commit removes the existing default_twenty_four_hour_time field in
Realm table which was used to set the twenty_four_hour_time setting of
new user on joining and instead we now use the twenty_four_hour_time
field of RealmUserDefault table for the same.

With some tweaks by tabbott to clarify the documentation.
2021-09-23 10:44:42 -07:00
Alya Abbott 0f9d0f5a86 help_docs: Reorganize notification docs under three umbrella pages.
With minor URL migration work by Eeshan Garg.
2021-09-22 16:46:46 -07:00
Mateusz Mandera 491f763f4e models: Improve conversion of CustomProfileField values.
These values are currently either a string already or a List[int]. We
should do the conversion in
do_update_user_custom_profile_data_if_changed properly: if the value is
already a string, it can be used directly - if it's not, orjson.dumps is
a more future-proof way of converting than str(). Using orjson.dumps
here also allows us to change the converter of the USER type
CustomProfileField to orjson.loads, which is nicer to have than
ast.literal_eval.
While orjson.dumps() and str() give the same output when
given the special case of List[int],
ast.literal_eval was previously used due to orjson.loads not being
a good inverse function to str in general. That gets straightened out
now.
2021-09-22 16:22:46 -07:00
Mateusz Mandera cacff28578 types: Fix declared type of custom profile field values.
None of the existing custom profile field types have the value as an
integer like declared in many places - nor is it a string like currently
decalred in types.py. The correct type is Union[str, List[int]]. Rather
than tracking this in so many places throughout the codebase, we add a
new ProfileDataElementValue type and insert it where appropriate.
2021-09-22 16:22:46 -07:00
Mateusz Mandera 91ea21a3fc actions: Fix type-incorrect custom profile field value assignment.
The old assignment is incorrect - field_value.value is a TextField() and
should always be a string. This didn't strictly break anything, because
django converts the value to a string when .save()ing to the db, but
field_value.value persists as a non-string for the rest of this
codepath. After fixing this, the small codeblock in
notify_user_update_custom_profile_data handling conversion of
field_value.value to a string becomes redundant.

We're assured that we're not breaking event format by the test
test_custom_profile_field_data_events in test_events.py.
2021-09-22 16:22:46 -07:00
Alya Abbott c7544d620d user docs: Fix missing tab name on /help/getting-your-organization-started-with-zulip. 2021-09-22 14:29:44 -07:00
Alya Abbott b773048031 user docs: Add documentation for configuring new user defaults.
Also remove a redundant link on customize-settings-for-new-users page.
2021-09-21 16:43:35 -07:00
Aman Agrawal 233d250eff do_make_stream_web_public: Send update to client.
Send update event to client after a stream is made web public.

This has been documented in the API documentation since feature level
73; previously the value was always false.
2021-09-21 12:16:10 -07:00
Aman Agrawal 5138652810 update_stream_backend: Add ability to make streams web public.
We allow clients to make existing streams web public via the API.

This feature is still disabled via settings in production
environments, because we may have additional policy rules or UI
warnings we wish to add to this sort of conversion.
2021-09-21 12:16:09 -07:00
Aman Agrawal 6a78112940 subscribe: Allow web public stream creation via the API.
User can now create web public stream via the /subscribe API.
So, when a web public stream present in the API request does not
exist, it will be created now by specifying the is_web_public
parameter. The parameter would have been ignored without this
commit.
2021-09-21 11:20:36 -07:00
Tim Abbott eb62693d26 list_to_streams: Use simpler if statement flow.
Since each if statement just raises an exception if triggered,
removing the else blocks makes the logic more readable.
2021-09-21 11:06:05 -07:00
Tim Abbott 71b8a1794a streams: Use standard error message when requiring owner.
The new error message is more clear about why, "User cannot create
stream with this settings." was bad English, and in any case removing
an unnecessary string is always an improvement for translators.
2021-09-21 11:05:30 -07:00
Eeshan Garg 5839f16969 markdown: Run settings_tab/relative links extensions after include.
Recently, we discovered that our settings_tab/relative Markdown
directives didn't work when they were in a macro that was included
in another Markdown file. Note that without this commit, the
/help/create-your-organization-profile page is broken. This commit
changes the respective priorities of these two extensions such that
these directives are rendered *after* the macro is included in
another file.

Thanks to Alya Abbott for reporting this bug!
2021-09-20 16:57:43 -07:00
Eeshan Garg bfbd77ca5c markdown: Organize preprocessor priorities in one place.
All of our custom Markdown extensions have priorities that govern
the order in which the preprocessors will be run. It is more
convenient to have these all in one file so that you can easily
discern the order at first glance.

Thanks to Alya Abbott for reporting the bug that led to this
refactoring!
2021-09-20 16:57:43 -07:00
Alya Abbott 2f3ebb5b16 help: Merge "Change who can add custom emoji" into "Custom emoji" page. 2021-09-17 18:08:59 -07:00
Alya Abbott 302aba035a help: Rename add-custom-emoji -> custom-emoji. 2021-09-17 18:08:59 -07:00
Abhijeet Prasad Bodas 743712c267 user_topic: Filter on visibility_policy in muted_topic code.
This is the final step required for it to be possible for us to add
UserTopic rows in the future with a differen visibility_policy.

Fixes #19272.
2021-09-17 12:14:28 -07:00
Abhijeet Prasad Bodas 4455dac424 models: Use default db table name for UserTopic.
Also update the realm import/export code and tests accordingly.
2021-09-17 12:14:28 -07:00
Abhijeet Prasad Bodas 2aea944a7e models: Rename UserTopic.date_muted to last_updated.
This is a follow-up to #19388.

We will in the future allow patch requests to change the visibility
of an existing topic, so `last_updated` is better name for this field.

This commit does not affect the API or events in any way, but only the
database.
2021-09-17 12:14:28 -07:00
Alya Abbott 310b8736af user docs: Add a bunch of "getting started" content. 2021-09-16 11:41:43 -07:00
Mateusz Mandera 05fe62c96c docs: Adjust phrasing of "From your desktop, click on the gear...".
We actually mean the main Zulip UI here, so "from your desktop" sounds
potentially misleading; reodering the phrasing makes the meaning
unambiguous.
2021-09-16 10:47:56 -07:00
Tim Abbott 39c897a2b0 help: Rename about-streams-and-topics to streams-and-topics.
This better matches the title of the page and more generally our
conventions around naming /help/ articles.  We include a redirect
because this is referenced from Welcome Bot messages, and we
definitely don't want those links to break.
2021-09-15 09:48:36 -07:00
Alex Vandiver 8c72959951 push_notifications: Handle empty rendered_messages.
This parallels fe25517295, but for mobile notifications.  It also
adds a test, which verifies that such content does not crash either
mobile or email notifications.
2021-09-15 09:45:38 -07:00
Alex Vandiver 039b869ca5 email_notifications: Fix inline-ing of image-URL-only messages.
fe25517295 adjusted the email_notifications codepath to use
`lxml.html.fragment_fromstring` method when parsing
`rendered_content`, but left the tests using a helper which called
`fromstring`.

Switching the tests to match the code as run reveals a bug -- using
`drop_tree` on all `message_inline_image` classes now _does_ remove
all of a top-level image-URL-only message.  Previously, such messages
were "safe" from the block that calls `drop_tree` only by dint of
`drop_tree` being a silent no-op for the root element.  When parsed
using `fragment_fromstring`, they are no longer the root, and as such
an empty message results.

Reorder relative_to_full_url to check for only one `message_inline_image`
within the top `<div>`, and only run the `drop_tree` path in the
alternate case.  Tests must be adjusted for their output now including
one more layer of `<div>`.
2021-09-15 09:45:38 -07:00
Mateusz Mandera 5d54cd1041 tests: Use a HttpRequest object in assert_login_failure.
Our convention is to always have authenticate() called with a request
object. We need to be consistent with that in tests too, to avoid test
failures resulting from breaking that assumption.
We modify assert_login_failure to call client.login() in the same way as
the other similar helpers - with a properly initialized HttpRequest
instance.
2021-09-14 15:39:41 -07:00
Aman Agrawal dff4ab0daf spectators: Add comments and assertions on security model.
These tweaks help make reasoning about the spectators security model
easier to understand.
2021-09-14 10:33:14 -07:00
Riken Shah 8c31e6f96e emoji: Add backend changes to support still image for animated emojis.
Now, when we add a custom animated emoji to the realm
we also save a still image of it (1st frame of the gif). So
we can avoid showing an animated emoji every time.
2021-09-12 07:13:04 +00:00
Mateusz Mandera ad188130ba do_send_confirmation_email: Make invite_expires_in_days optional.
create_confirmation_link has validity time as an optional argument,
because it has reasonable defaults. Thus it's a better API for
do_send_confirmation_email to make this optional as well, allowing
relying on create_confirmation_link's defaults.
2021-09-10 16:53:03 -07:00
Mateusz Mandera 3205f680c1 do_invite_users: Turn some args into kwargs-only. 2021-09-10 16:53:03 -07:00
shanukun 8c1ea78d7d invite: Extend invite api for handling expiration duration.
This extends the invite api endpoints to handle an extra
argument, expiration duration, which states the number of
days before the invitation link expires.

For prereg users, expiration info is attached to event
object to pass it to invite queue processor in order to
create and send confirmation link.
In case of multiuse invites, confirmation links are
created directly inside do_create_multiuse_invite_link(),

For filtering valid user invites, expiration info stored in
Confirmation object is used, which is accessed by a prereg
user using reverse generic relations.

Fixes #16359.
2021-09-10 16:53:03 -07:00
Eeshan Garg 85b1f1bed9 email: Update follow-up day 1 emails to mention demo orgs.
This is a part of #19523.
2021-09-10 16:31:54 -07:00
Eeshan Garg bf9c35ded4 onboarding: Mention demo orgs in Welcome Bot's PMs.
This is a part of #19523.
2021-09-10 16:31:54 -07:00
Abhijeet Prasad Bodas 17b8d53612 email notifs: Update scheduled timestamps after batching period change.
The API for changing the batching period was added in
5db4fe8652.

This is a follow up to that commit. We also update the timestamps for
existing scheduled email notifications entries so that the effect of
changing the setting is immediate.

Part of #15280
2021-09-10 13:25:47 -07:00
Mateusz Mandera f064e3ebac auth: Ensure a realm can't be created on SOCIAL_AUTH_SUBDOMAIN. 2021-09-10 10:47:15 -07:00
Anders Kaseorg c14549f275 name_restrictions: Reserve ‘mg’ and ‘front-mail’.
These hostnames only have MX records for Mailgun and Front, and will
not work as a Zulip organization.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-09-10 10:25:56 -07:00
Sahil Batra c7cb983ebd settings: Move check_settings_values to user_settings.py.
This commit moves check_settings_values to user_settings.py
from validator.py such that we can import the functions at
the top without any issue of cyclic imports.
2021-09-09 15:03:55 -07:00
Sahil Batra 88346949b5 messages: Do not allow mentioning system user groups.
We do not allow mentioning system user groups for now
because this can lead to circumventing the wildcard
mention restrictions. It will be enabled once we add
a setting to control that.

This is implemented by just ignoring it as one of the
mentioned user group even if the message content
inlcudes the mention syntax for it and the message
is sent normally.

We still keep the for_mention parameter for accessing
user group while sending email and push notifications
as mentioning system user groups will be allowed in
future.
This commit also removes the test for email notifications
for system user groups as we are not allowing mentioning
them.

This commit is only for backend change as we already
exclude the system groups from mention typeaheads and
other UI.
2021-09-09 11:25:33 -07:00
Parth 9ed707c34b authentication: Fix placeholder realms for redirects.
The name of the new realm created as a tombstone after renaming
a realm's subdomain is the constant 'placeholder-realm'.
This would confuse the user when shown the deactivation notice
and asking to join the realm at a new subdomain.
This PR replaces it with the original realm name to avoid confusion.
Fixes: #19677
2021-09-09 11:02:45 -07:00
sahil839 8bab712cb4 create_user: Initialize settings according to realm-level defaults.
This commit modifies the copy_user_settings code such that instead
of source user profile, we can have two types of sources - a user
profile and RealmUserDefault table of realm and then set the
settings from RealmUserDefault only is there is no user profile
as a source.

We also rename copy_user_settings to copy_default_settings for
clarity.
2021-09-09 10:55:19 -07:00
Sahil Batra 693d58265e realm: Add 'PATCH /realm/user_settings_defaults' endpoint.
The realm-level default value of settngs for new users will
be updated using this endpoint.
2021-09-09 10:55:18 -07:00
Sahil Batra 17087cf06f actions: Add do_set_realm_user_default_setting.
This commit adds do_set_realm_user_default_setting which
will be used to change the realm-level defaults of settings
for new users.

We also add a new event type "realm_user_settings_defaults"
for these settings and a "realm_user_settings_default" object
in '/register' response containing all the realm-level default
settings.
2021-09-09 10:38:38 -07:00
sahil839 7d64a9053b models: Ensure every realm has a RealmUserDefault object.
Because we create all realms with do_create_user (including in the
test suite), we just need to change that function, add a migration for
existing realms, and ensure the data import code path correctly
creates these objects.

Note that the import code path will create a RealmUserDefault row with
default values if it is not present in the import data, which is
important for importing data from other tools like Slack.
2021-09-09 10:28:44 -07:00
Sahil Batra 97f41b5abd users: Change type of enable_marketing_emails parameter in create_user.
This commit changes the type of enable_marketing_emails parameter of
create_user to Optional[bool].
The value of this parameter will be None in certain cases when user
registers through SSO and 'TERMS_OF_SERVICE=False' when there will
be no registration form and thus no value of enable_marketing_emails.
2021-09-09 10:15:07 -07:00
Sahil Batra 03a0cfda64 settings: Set enable_marketing_emails after copying user settings.
We set the enable_marketing_emails setting after copying user
settings to override the value selected in registration form.
This change is also necessary because enable_marketing_emails
field is present in RealmUserDefault to avoid copying code
but we do not use this value actually and instead we want
the setting to be set according to the value in registration
form.

We set this setting only for non-bot users since we generally
do not set any settings for bots.
2021-09-09 10:15:07 -07:00
Sahil Batra 2eec0772fb user_settings: Extract setting values checks to a function.
We extract the checks for default_language, notification_sound,
and email_notifications_batching_period_seconds setting values
in json_change_settings to a new function check_settings_values.
2021-09-09 10:15:07 -07:00
Tim Abbott c5261af2dc migrations: Fix system bot realm not having a name.
This prevented migration 0345
(517c2ed39d / #19696) from applying on
systems that were created after the refactoring that resulted in the
system bot realm potentially having null as its name.

(We've already confirmed that normal realms, created via
`do_create_realm`, shouldn't be able to have this unusual state).
2021-09-09 09:50:43 -07:00
Tim Abbott 545911b051 markdown: Remove useless locless_schemes check.
This check was copied from upstream python-markdown's "safe mode"
before they removed that feature.  The upstream history is that they
introduced this check in
2db5d1c8e4,
which was not a complete security check, and then added the
immediately following check (with an allowlist of schemes) in
0b4ffbb60e.

Their first, incomplete check provides no security benefit and makes
the code hard to reason about, so we remove it.
2021-09-09 09:03:40 -07:00
rht c24ab8c4d3 markdown: Expand list of safelisted URL schemes to match HTML spec. 2021-09-09 09:03:40 -07:00
Sahil Batra 9c4eb764e2 create_user: Do not set enter_sends value twice.
enter_sends is already included in property_types
dict, so there is no need to set it again using
setattr in copy_user_settings.
2021-09-09 09:03:06 -07:00
Sahil Batra 8b711695cb event_schema: Use notification_settings_legacy to get type.
The 'update_global_notifications' type event is sent only for
existing settings and will not be sent for new settings, so we
should use notification_settings_legacy dict to check the type
of setting value in check_update_global_notifications instead
of notification_settings_types dict.
2021-09-09 09:03:06 -07:00
Sahil Batra 526de3f7d1 settings: Remove unnecessary loop of notification_setting_types.
We still used notification_setting_types in copy_user_settings
function of create_user.py and in a test in test_event_system.py.
It is not required to do so since we have added all settings in
property_types already and we loop over property_types at both
these places which includes all settings.
2021-09-09 09:03:06 -07:00
Sahil Batra 2f61afea9f settings: Remove do_change_notification_settings function.
This commit removes the do_change_notification_settings
function and we use do_change_user_setting directly to
change all the user settings now.
2021-09-08 11:04:44 -07:00
Sahil Batra 991efaf450 actions: Make acting_user manadatory kwarg for do_change_user_setting. 2021-09-08 11:04:44 -07:00
Sahil Batra 550d97a593 settings: Refactor callers of do_change_user_setting to pass acting_user. 2021-09-08 11:04:44 -07:00
Eeshan Garg f0ea002d94 events: Add demo_organization_scheduled_deletion_date to /register.
This commit adds `demo_organization_scheduled_deletion_date` to
the `realm` section of the `/register` response so that it is
available to clients when enabled.

This is a part of #19523.
2021-09-07 17:40:33 -07:00
Anders Kaseorg 66ad6a4583 docs: Inline code spans are not blocks.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-09-07 16:12:39 -07:00
Tim Abbott dd6cc32ae5 do_change_notification_settings: Merge into do_change_settings.
We preserve the function as a small wrapper until we can resolve the
TODO noted in the comment.
2021-09-07 10:49:56 -07:00
Tim Abbott a5d46e5cab do_change_notification_settings: Add conditional around RealmAuditLog work. 2021-09-07 10:49:56 -07:00
Tim Abbott fecdc234bf models: Rename setting-changed RealmAuditLog entry.
We will likely in the future want to start creating these for all
settings changes, and this new name will make the code more readable
when we do so.
2021-09-07 10:49:56 -07:00
Tim Abbott bd6f12329e do_change_notification_settings: Rename value->setting_value.
This is for consistency with do_change_user_setting; it'll make the
diffs a lot more readable when we merge these functions.
2021-09-07 10:49:56 -07:00
Tim Abbott 54cbdd8c46 do_change_notification_settings: Rename name->setting_name.
This is for consistency with do_change_user_setting; it'll make the
diff a lot more readable when we merge these functions.
2021-09-07 10:49:51 -07:00
Dinesh 9443e01a5d refactor: Rename do_set_user_display_setting to do_set_user_setting. 2021-09-07 10:16:42 -07:00
Dinesh 430c5cb8e7 user_settings: Create _legacy dicts for existing settings.
Since 84742a0, all settings are sent in the `user_settings` dictionary
which were previously sent inline with other fields in /register
response.

In order to simplify the process of adding new personal settings, we
want to transition to a world where new settings only need to consider
the `property_types` object, and code that needs to reference the
legacy behavior interacts with an object with `legacy` in its name.

This way, contributors working on new settings don't need to think
about the legacy code paths at all.

See https://chat.zulip.org/#narrow/stream/378-api-design/topic/user.20settings.20response.20in.20.2Fregister
to understand this better.
2021-09-07 10:14:45 -07:00
Anders Kaseorg 646c04eff2 Rename default branch to ‘main’.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-09-06 12:56:35 -07:00
Aman Agrawal 34a37f55d6 spectators: Rename is_web_public_compatible functions. 2021-09-06 09:00:16 -07:00
Aman Agrawal 3e7538b974 filter: Copy is_web_public_compatible from server to frontend.
This will be used to check if the narrow being requested by
spectator requires authentication without requesting the server.
Having this check locally, makes this process look snappy to
the user and doesn't result in 404s in the browser log.
2021-09-06 09:00:16 -07:00
Anders Kaseorg 9399b95fec push_notifications: Remove redundant APNs retry loop.
aioapns already has a retry loop.  By default it retries forever on
ConnectionError and ConnectionClosed, so our own retry loop would
never be reached.  Remove our retry loop, and configure aioapns to
retry APNS_MAX_RETRIES times on ConnectionError like the previous
version did.  It still retries forever on ConnectionClosed; that’s not
configurable but probably fine.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-09-03 11:49:33 -07:00
Eeshan Garg f5c26990c2 settings: Add constant for demo org deadlines.
We set the 30 days deadline timedelta for demo orgs as a constant
in default_settings.py so that it can be overridden in tests.
2021-09-03 09:06:29 -07:00
PIG208 e73d55af91 push_notifications: Refactor trigger from Message objects.
This is a cleaner way to reduce monkey-patched attributes we added
to the Message objects.
2021-09-03 08:48:45 -07:00
PIG208 53888e5a26 request: Refactor ZulipRequestNotes to RequestNotes.
This utilizes the generic `BaseNotes` we added for multipurpose
patching. With this migration as an example, we can further support
more types of notes to replace the monkey-patching approach we have used
throughout the codebase for type safety.
2021-09-03 08:48:45 -07:00
PIG208 dba7b1e3a7 request: Extract generic BaseNotes from RequestNotes.
The motive of adding `BaseNotes` was to support monokey patching
temporary attributes to objects (such as `.trigger` on `Message`) when
working on the django-stubs migration in #18777.
2021-09-03 08:47:51 -07:00
Tim Abbott 356e6e5018 status: Extract format_user_status helper.
This will allow us to reuse this formatting logic for a single-user
version of this endpoint.
2021-09-02 16:50:25 -07:00
rht a13f3d4386 import_realm: Use generate_message_upload_path() to get upload file path.
This way, we no longer have to manually keep the upload path code in
sync with the upload path code in zerver/lib/upload.py.
This was originally suggested in
https://github.com/zulip/zulip/pull/19478#issuecomment-911479530.

This change fixes a bug when importing into a server using the local
file uploads backend, where the `import_realm.py` copy wasn't using
our standard 256-directory approach to avoid putting too many files in
a single directory.
2021-09-02 16:36:48 -07:00
rht 6ff659d199 upload: Extract generate_message_upload_path helper.
This helper will let us avoid copying this logic in the data import
code path.
2021-09-02 16:31:08 -07:00
Alex Vandiver 094f22e6b4 notifications: Add safeties to prevent incorrect notifications.
de04f0ad67 changed now notifications recipients were calculated, in
a manner that caused them to be sent when they should not have been.
ac70a2d2e1 was supposed to resolve this, but appears to have been
insufficient, as all three of these cases have been observed to still
happen.

Add safety checks immediately before notification, until the
underlying logic error can be sussed out.
2021-09-02 02:49:10 -07:00
Alex Vandiver 66aa2a2505 fetch-contributor-data: Use builtin backoff.
This correctly handles connection timeouts, not just non-200 status
codes.
2021-09-01 05:34:13 -07:00
Alex Vandiver bf9780267d outgoing_http: Give an easy way to configure retries.
The default is kept as no retries.  Since retries with exponential
backoff are a good thing to make easy, the int form defaults to
setting a backoff_factor.

Unfortunately, urllib3 retry backoff does not implement jitter.
Switching this to use the `backoff` library[1] rather than urllib3's
native Retry is left as future extension.

[1] https://pypi.org/project/backoff/
2021-09-01 05:34:13 -07:00
Alex Vandiver 4d428490fd outgoing_http: Use OutgoingSession subclasses in more places.
This adds the X-Smokescreen-Role header to proxy connections, to track
usage from various codepaths, and enforces a timeout.  Timeouts were
kept consistent with their previous values, or set to 5s if they had
none previously.
2021-09-01 05:34:13 -07:00
Priyansh Garg 1e51c23494 markdown: Remove unnecessary checks for zulip_message.
This commits removes some unnecessary checks for `self.md.zulip_message`,
which were put there historically, as earlier we used to add the additional
properties like mentions_user_ids, alert_words, etc. to Message dict
only. These were later moved to MessageRenderingResult class in commit
75cea329b but the checks weren't removed.

This is important because while rendering the messages imported from
other chat tools (like Rocket.Chat), the Message dict is not passed to
the markdown, due to which the checks for `self.md.zerver_message` fails
and hence, things like user mentions, stream/topic mentions are not
rendered in the imported messages properly.
2021-08-31 16:53:42 -07:00
Alex Vandiver 5e5166d872 email_mirror: Downgrade a couple ZulipEmailForwardErrors.
These errors may occur in the course of normal operations, and
shouldn't generate a message in the error logs.
2021-08-31 16:37:54 -07:00
Alex Vandiver 422be80d94 email_mirror: Downgrade ZulipEmailForwardUserError to info.
This does not need to clog the logs as much, but may be useful from a
product decision standpoint.
2021-08-31 16:37:54 -07:00
Alex Vandiver be669c8d98 email_mirror: Move ZulipEmailForwardUserError into email_mirror_helpers. 2021-08-31 16:37:54 -07:00
Alex Vandiver 621d0e5123 send_email: Log IP address sources (and more realms) of send_email. 2021-08-31 16:36:42 -07:00
Anders Kaseorg 817146c28b python: Upgrade SQLAlchemy from 1.3.24 to 1.4.23.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-31 06:47:39 -07:00
Alex Vandiver 6c15df68e8 downloads: Serve desktop downloads from desktop-download.zulip.com.
This makes them work for sites which block github.com.
2021-08-28 23:08:45 -07:00
Alex Vandiver fe25517295 email_notifications: Handle empty rendered_messages.
The transforms called from `build_message_payload` use
`lxml.html.fromstring` to parse (and stringify, and re-parse) the HTML
generated by Markdown.  However, this function fails if it is passed
an empty document.  "empty" is broader than just the empty string; it
also includes any document made entirely out of control characters,
spaces, unpaired surrogates, U+FFFE, or U+FFFF, and so forth.  These
documents would fail to parse, and raise a ParserError.

Using `lxml.html.fragment_fromstring` handles these cases, but does by
wrapping the contents in a <div> every time it is called.  As such,
replacing each `fromstring` with `fragment_fromstring` would nest
another layer of `<div>`.

Instead of each of the helper functions re-parsing, modifying, and
stringifying the HTML, parse it once with `fragment_fromstring` and
pass around the parsed document to each helper, which modifies it
in-place.  This adds one outer `<div>`, requiring minor changes to
tests and the prepend-sender functions.

The modification to add the sender is left using BeautifulSoup, as
that sort of transform is much less readable, and more fiddly, in raw
lxml.

Partial fix for #19559.
2021-08-25 15:50:55 -07:00
Alex Vandiver 42e3c4e6ec email_notifications: Rename append_sender_to_message to prepend.
The sender goes on the beginning, which is prepending to the message.
2021-08-25 15:50:55 -07:00
Eeshan Garg c9861b3c74 marketing_emails: Ask for user's consent at sign-up. 2021-08-20 06:43:26 -07:00
PIG208 fa09404dd7 typing: Use assertions for responses when appropriate.
This is part of #18777.
2021-08-20 06:02:56 -07:00
PIG208 04f5f25478 typing: Replace `File` with `IO[bytes]`. 2021-08-20 06:02:28 -07:00
PIG208 7386918539 typing: Use accurate type hints for dictionaries.
This fixes the mypy errors related to dictionaries with django-stubs.
2021-08-20 06:02:28 -07:00
PIG208 3b11c36ed9 typing: Fix function signatures.
This fixes mypy errors for function signatures discovered with
django-stubs.
2021-08-20 05:54:19 -07:00
PIG208 71427239d0 typing: Replace CursorObj by CursorWrapper. 2021-08-20 05:54:19 -07:00
PIG208 254f706465 typing: Fix argument type for models in function signatures. 2021-08-20 05:54:19 -07:00
PIG208 aa9d73c9f6 typing: Improve typing with assertions.
This fixes some mypy errors discovered with django-stubs.
2021-08-20 05:54:19 -07:00
PIG208 9d8e80a4d7 push_notifications: Refactor testcases to fix mypy errors.
This fixes errors found with django-stubs and it is a part of #18777.

It mostly renames variables and adds non-check assertions.
2021-08-20 05:54:19 -07:00
PIG208 bb36bd8b6b profile_request: Replace MockRequest with HostRequestMock.
Since previously we use a custom mock request that doesn't inherit
HttpRequest, there are some typing problems when we use it.
2021-08-20 05:54:19 -07:00
PIG208 460119986b management: Fix typing for management scripts.
There are some remaining errors related to the django `Manager[T]` and
the `List[T]` type that we use to annotate the `Manage[T]` objects.
2021-08-20 05:54:18 -07:00
Eeshan Garg dea4187aff devlogin: Add support for creating development demo realms.
This is a part of #19523.
2021-08-19 03:09:36 -07:00
Sahil Batra 5f5c88a4e2 user_groups: Add 'is_system_group' field to objects passed to clients. 2021-08-19 02:56:43 -07:00
Sahil Batra 4c290a49d3 user_groups: Do not allow editing system user groups from API.
We do not allow any user to edit the system user groups (including
renaming, deleting, adding or removing members, etc.) from the
API. These user groups will change only by the code when a new
user is added or role of a user is changed.

This is implemented by rejecting access_user_group_by_id always
except the case when it is use to get the user group for sending
email and push notifications, as we would need to send notifications
to the mentioned user group.
2021-08-19 02:54:29 -07:00
Sahil Batra 0e96a92a6d user_groups: Make description as keyword-only arg in create_user_group.
We make the description parameter in create_user_group as keyword-only
to improve readability. We would also keep the is_system_group
parameter which will be added in future keyword-only.
2021-08-19 02:54:29 -07:00
Anders Kaseorg 4b83003b3e html_diff: Remove unused highlight_with_class function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:53:47 -07:00
Anders Kaseorg aa0768a1a4 validator: Remove unused check_or function.
check_union is more general.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:52:24 -07:00
Anders Kaseorg 4fe030e6ea validator: Remove unused to_positive_or_allowed_int function.
The last use was removed in 1562ec758e.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:52:24 -07:00
Anders Kaseorg 404ef284bb validator: Remove unused check_tuple function.
Tuples cannot be deserialized from JSON.

While we do use these validators for other things, like event
dictionaries, we have migrated the API away from using those.  The
last use was removed in 4f3d5f2d87

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:41 -07:00
Anders Kaseorg f3e5ed57ae utils: Remove unused split_by function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 58b7a4eb44 utils: Remove unused query_chunker function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 271333301d user_groups: Remove unused check_remove_user_from_user_group function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 4e366bfff5 user_groups: Remove unused check_add_user_to_user_group function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 57acac12fa user_groups: Remove unused user_groups_in_realm function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg fdbde9f9c2 push_notifications: Remove unused num_push_devices_for_user function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg b2239e45ac statistics: Remove unused seconds_usage_between function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 27325eb2ae exceptions: Remove unused to_json method of JsonableError.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 79f7f9b8d9 actions: Remove unused get_emails_from_user_ids function.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 6ae5be6e75 exceptions: Remove AbstractEnum in favor of enum.auto.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 0d061f44c1 actions: Remove acting_client parameter from bulk_remove_subscriptions.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 0b795e492f thumbnail: Remove unused is_camo_url parameter.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Anders Kaseorg 4206e5f00b python: Remove locally dead code.
These changes are all independent of each other; I just didn’t feel
like making dozens of commits for them.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-19 01:51:37 -07:00
Alex Vandiver 56344e4765 scheduled_email: Only call .save() if necessary.
Calling `email.save()` is only needed if we altered `email.address`;
it is unnecessary if we called `email.users.add(...)` which will have
done its own INSERT.
2021-08-19 00:44:33 -07:00
Alex Vandiver d4f6b93859 scheduled_email: Create ScheduledEmail objects in a transaction.
This fixes two bugs: the most obvious is that there is a race where a
ScheduledEmail object could be observed in the window between creation
and when users are added; this is a momentary instance when the object
has no users, but one that will resolve itself.

The more subtle is that .save() will, if no records were found to be
updated, _re-create_ the object as it exists in memory, using an
INSERT[1].  Thus, there is a race with `deliver_scheduled_emails`
between when the users are added, and when `email.save()` runs:

 1. Web request creates ScheduledEmail object
 2. Web request creates ScheduledEmailUsers object
 3. deliver_scheduled_emails locks the former, preventing updates.
 4. deliver_scheduled_emails deletes both objects, commits, releasing lock
 5. Web request calls `email.save()`; UPDATE finds no rows, so it
    re-creates the ScheduledEmail object.
 6. Future deliver_scheduled_emails runs find a ScheduledEmail with no
    attending ScheduledEmailUsers objects

Wrapping the logical creation of both of these in a single transaction
avoids both of these races.

[1] https://docs.djangoproject.com/en/3.2/ref/models/instances/#how-django-knows-to-update-vs-insert
2021-08-19 00:44:33 -07:00
Alex Vandiver 4c518c2bba scheduled_email: Consistently lock users table.
Only clear_scheduled_emails previously took a lock on the users before
removing them; make deliver_scheduled_emails do so as well, by using
prefetch_related to ensure that the table appears in the SELECT.  This
is not necessary for correctness, since all accesses of
ScheduledEmailUser first access the ScheduledEmail and lock it; it is
merely for consistency.

Since SELECT ... FOR UPDATE takes an UPDATE lock on all tables
mentioned in the SELECT, merely doing the prefetch is sufficient to
lock both tables; no `on=(...)` is needed to `select_for_update`.

This also does not address the pre-existing potential deadlock from
these two use cases, where both try to lock the same ScheduledEmail
rows in opposite orders.
2021-08-19 00:44:33 -07:00
Alex Vandiver ebaafb32f3 send_email: Change clear_scheduled_emails to only take one user.
No codepath except tests passes in more than one user_profile -- and
doing so is what makes the deduplication necessary.

Simplify the API by making it only take one user_profile id.
2021-08-19 00:44:33 -07:00
Abhijeet Prasad Bodas ac70a2d2e1 notifications: Fix unnecessary wildcard mention notifications.
This fixes a bug where email notifications were sent for wildcard
mentions even if the `enable_offline_email_notifications` setting was
turned off.
This was because the `notification_data` class incorrectly considered
`wildcard_mentions_notify` as an indeoendent setting, instead of a wrapper
around `enable_offline_email_notifications` and `enable_offline_push_notifications`.

Also add a test for this case.
2021-08-13 09:48:18 -07:00
Alex Vandiver fc9e5f5187 github: Use logging.exception so we know which exception happened. 2021-08-10 22:38:18 -07:00
Anders Kaseorg 1bdb7b1141 mypy: Add boto3-stubs.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
Anders Kaseorg bfdb2f4628 export: Fix error message generation in _check_key_metadata.
There is no key.name.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
Anders Kaseorg 05124737f7 mypy: Add backoff-stubs.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
Anders Kaseorg 09564e95ac mypy: Add types-psycopg2.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
Anders Kaseorg 5c90522e69 mypy: Add types-Pillow.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
Anders Kaseorg 14f0594795 upload: Replace exif_rotate with Pillow exif_transpose.
Fixes #18599.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-09 20:32:19 -07:00
PIG208 0dac524ea4 registration: Refactor view functions in registration.py to use REQ. 2021-08-08 17:11:18 -07:00
PIG208 15eeb2cb25 message: Refactor send_message_backend to use REQ. 2021-08-08 17:11:18 -07:00
PIG208 94685e1afb analytics: Refactor the support view to use REQ. 2021-08-08 17:11:18 -07:00
Anders Kaseorg 7f0381d4c7 outgoing_http: Fix type annotations.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-05 18:34:38 -05:00
Tim Abbott cde86fbaca send_email: Move logging after dry-run abort.
Previously, the output would make it look like we sent an actual email
to the first user in the dry_run output, which is very confusing.

The `dry_run` code path already prints all the accounts that would
have been emailed at the end, so there's no reason to have this line
before the dry_run check.

Additionally, we move after the `get_connection` check because
failures at that stage shouldn't result in logging an attempt to send
an email.
2021-08-05 10:15:49 -07:00
tushar912 83f6557f43 integrations: Add SonarQube webhook integration.
Fixes #13395.
2021-08-05 09:53:42 -07:00
Anders Kaseorg 3a6d44b691 mention: Simplify init_user_group_data using prefetch_related.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-05 09:20:34 -07:00
Anders Kaseorg 806494da06 markdown: Stream and parse incrementally in fetch_open_graph_image.
This way we can stop reading as soon as we get to the body.  Also,
send an Accept header, check that the request was actually successful,
use lxml.etree.iterparse instead of a broken hand-rolled state
machine, and support XHTML, all for negative 28 lines of code.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-05 09:17:32 -07:00
Priyansh Garg 0a875c1c4c markdown: Fix jpeg extension in `IMAGE_EXTENSIONS`. 2021-08-05 08:54:02 -07:00
Anders Kaseorg 905de1fdba email_notifications: Build HTML elements correctly.
correct_parser(f"incorrectly {generated} <html> string") is still
incorrect.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-04 11:29:20 -07:00
Anders Kaseorg 19424146d4 email_notifications: Fix make_emoji_img_elem type.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-04 11:29:20 -07:00
Steve Howell 45f6c8d27f page load: Remove sender_ids in unread messages for streams. 2021-08-04 11:44:00 -04:00
Anders Kaseorg 42fa62e563 Revert "time_widget: Make the generated time string more readable."
This reverts commit 1965584eec.

This syntax has a bad interaction with table syntax and needs to be
rethought.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-03 16:45:31 -07:00
Gaurav Pandey 75bfdadf8c populate_db: Generate resolved topics for testing.
To try to match normal workflow, some streams have many resolved
topics and others have few.
2021-08-03 16:42:09 -07:00
Lefteris Kyriazanos 2b70e88fda integrations: Add basic open collective integration.
Add basic open collective integration for the user donation
event.
Fixes #18319
2021-08-03 16:09:33 -07:00
Ganesh Pawar 1965584eec time_widget: Make the generated time string more readable.
Before: <time:2021-07-14T00:14:00-07:00>
After: <time:2021-07-14|00:14:00|UTC-07:00>

Fixes #19205
2021-08-02 23:17:01 -07:00
Anders Kaseorg 498d2b48d9 fenced_code: Use find_lexer_class_by_name.
This is more efficient than get_lexer_by_name, since we don’t need to
instantiate the class just to get its name.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg 04feadd917 mypy: Add pika-stubs.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg 9f8ba913fd queue: Fix _on_connection_open_error type to accept reason: str.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg f7e2426fc5 queue: Fix ensure_queue type to accept a callback returning any object.
channel.basic_consume actually returns str.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg 5e355abe2e queue: Add missing imports.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg 87799177b5 queue: Fix channel type for TornadoQueueClient.
The BlockingChannel annotations in TornadoQueueClient were flat-out
wrong.  BlockingChannel and Channel have no common base classes.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg 5751479932 queue: Switch TornadoQueueClient to the new base QueueClient.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg bd6a2b149c queue: Split common part of SimpleQueueClient into new base class.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 22:31:46 -07:00
Anders Kaseorg fae92f2e3f actions: Convert TypedDict declaration to Python 3.6 style.
Generated by pyupgrade, with manual indentation adjustment for
https://github.com/asottile/pyupgrade/issues/507.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 15:53:52 -07:00
Anders Kaseorg 5483ebae37 python: Convert "".format to Python 3.6 f-strings.
Generated automatically by pyupgrade.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 15:53:52 -07:00
Anders Kaseorg ad5f0c05b5 python: Remove default "utf8" argument for encode(), decode().
Partially generated by pyupgrade.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 15:53:52 -07:00
Anders Kaseorg 3665deb93a python: Remove unnecessary intermediate lists.
Generated automatically by pyupgrade.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-08-02 15:53:52 -07:00
rht 9441bca282 import_realm: Explain the usage of the relative_path var of attachment_path. 2021-08-02 13:13:19 -07:00
Tim Abbott 24b1439e93 email_notifications: Avoid trying to email to bot users.
This fixes a regression in de04f0ad67.

We'll do a proper test in a follow-up commit; this is a quick fix to
make sure master works.

The emails will bounce, but it'll create all sorts of infrastructure
headaches.
2021-08-02 13:13:01 -07:00
Sahil Batra 998d710275 frontend: Add new user_settings module for user's settings.
We add a new user_settings module similar to page_params
module in frontend and use it to access user's personal
settings instead of page_params.
2021-08-01 15:30:17 -07:00
Sahil Batra e6f828a8e2 register: Send user_settings in response based on client capabilities.
We added "user_settings" object containing all the user settings in
previous commit. This commit modifies the code to send the existing
setting fields in the top-level object only if user_settings_object
client_capabilities field is False.
2021-08-01 15:30:17 -07:00
Sahil Batra 84742a040e api: Add "user_settings" object to '/register' response.
We add a "user_settings" object, containing all the user
settings, in the '/register' endpoint response for
better readability.
2021-08-01 15:30:17 -07:00
Sahil Batra 0364d0c8ca events: Add "user_settings_object" to client_capabilities.
This commit adds "user_settings_object" field to
client_capabilities which will be used to determine
if the client needs 'update_display_settings' and
'update_global_notifications' event.
2021-08-01 15:30:17 -07:00
Sahil Batra 7959ae3fab events: Add new event type 'user_settings' for updating user settings.
We send a event with type 'user_settings' on updating user's display
and notification settings.

The old event types - 'update_global_notifications' and
'update_display_settings', are still supported for backwards
compatibility.
2021-08-01 15:30:17 -07:00
Gaurav Pandey d89b4dcd0b api: Return zulip_merge_base alongside zulip_version.
Return zulip_merge_base alongside zulip_version
in `/register`, `/event` and `/server_settings`
endpoint so that the value can be used by other
clients.
2021-07-30 12:03:41 -07:00
Hemanth V. Alluri 6fee946a43 drafts: Send events to clients when drafts change.
With this, the core of the new drafts system is complete.
2021-07-30 10:41:52 -07:00
Hemanth V. Alluri c00089ac28 drafts: Add support for toggling drafts synchronization.
With changes mostly to the API documentation by tabbott.
2021-07-30 10:00:27 -07:00
Hemanth V. Alluri f1f0a26c37 drafts: Extract all of the real work to lib functions.
The main reason why this is needed is because this seems to be
convention and because we can't easily test event creation without
doing this.

Signed-off-by: Hemanth V. Alluri <hdrive1999@gmail.com>
2021-07-28 16:33:01 -07:00
Abhijeet Prasad Bodas de04f0ad67 notifications: Calculate PMs/mentions settings like other settings.
Previously, we checked for the `enable_offline_email_notifications` and
`enable_offline_push_notifications` settings (which determine whether the
user will receive notifications for PMs and mentions) just before sending
notifications. This has a few problem:

1. We do not have access to all the user settings in the notification
handlers (`handle_missedmessage_emails` and `handle_push_notifications`),
and therefore, we cannot correctly determine whether the notification should
be sent. Checks like the following which existed previously, will, for
example, incorrectly not send notifications even when stream email
notifications are enabled-
```
if not receives_offline_email_notifications(user_profile):
    return
```
With this commit, we simply do not enqueue notifications if the "offline"
settings are disabled, which fixes that bug.

Additionally, this also fixes a bug with the "online push notifications"
feature, which was, if someone were to:
* turn off notifications for PMs and mentions (`enable_offline_push_notifications`)
* turn on stream push notifications (`enable_stream_push_notifications`)
* turn on "online push" (`enable_online_push_notifications`)

then, they would still receive notifications for PMs when online.
This isn't how the "online push enabled" feature is supposed to work;
it should only act as a wrapper around the other notification settings.

The buggy code was this in `handle_push_notifications`:
```
if not (
    receives_offline_push_notifications(user_profile)
    or receives_online_push_notifications(user_profile)
):
    return

    // send notifications
```

This commit removes that code, and extends our `notification_data.py` logic
to cover this case, along with tests.

2. The name for these settings is slightly misleading. They essentially
talk about "what to send notifications for" (PMs and mentions), and not
"when to send notifications" (offline). This commit improves this condition
by restricting the use of this term only to the database field, and using
clearer names everywhere else. This distinction will be important to have
non-confusing code when we implement multiple options for notifications
in the future as dropdown (never/when offline/when offline or online, etc).

3. We should ideally re-check all notification settings just before the
notifications are sent. This is especially important for email notifications,
which may be sent after a long time after the message was sent. We will
in the future add code to thoroughly re-check settings before sending
notifications in a clean manner, but temporarily not re-checking isn't
a terrible scenario either.
2021-07-28 13:55:25 -07:00
Abhijeet Prasad Bodas 683c8507e4 models: Remove MutedTopic alias for UserTopic.
Part of #19272
2021-07-28 10:25:54 -07:00
Riken Shah 9fadd43830 user_status: Add backend changes to support status emoji.
In this commit:

* We update the `UserStatus` model to accept
`AbstractReaction` as a base class so, we can get all the
fields related to store status emoji.

* We update the user status endpoint
(`users/me/status`) to accept status emoji fields.

* We update the user status event to add status emoji
fields.

Co-authored-by: Yash Rathore <33805964+YashRE42@users.noreply.github.com>
2021-07-27 17:57:15 -07:00
Tim Abbott ed01ffadba tests: Fix leading slash in test exclusion as well. 2021-07-27 17:01:18 -07:00
sahil839 0d6f378ad7 help: Update documentation for add_custom_emoji_policy. 2021-07-27 16:41:23 -07:00
sahil839 1ce09d9db6 realm: Extend add_custom_emoji_policy to use COMMON_POLICY_TYPES.
This commit adds full members and moderators option for
add_custom_emoji_policy by using COMMON_POLICY_TYPES.
2021-07-27 16:41:23 -07:00
sahil839 4b1313a92b models: Replace add_emoji_by_admins_only with add_custom_emoji_policy.
This commit replaces boolean field add_emoji_by_admins_only with an
integer field add_custom_emoji_policy as we would also add full members
and moderators option for this setting in further commits.
2021-07-27 16:41:22 -07:00
Anders Kaseorg 17749cb608 archive: Remove non-functional archive code.
This removes a bunch of non-functional duplicate JavaScript, HTML, and
CSS that was interfering with maintenance on the functional originals,
because it was never clear how to update the duplicates or how to
check that you’d updated the duplicates correctly.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2021-07-27 16:25:24 -07:00
Sahil Batra 79b0ff5b23 events: Send enter_sends if update_display_settings in fetch_event_types.
We now send 'enter_sends' in response of '/register' endpoint if
'update_display_settings' is present in 'fetch_event_types' instead
of 'realm_user'.
2021-07-27 15:54:16 -07:00
Sahil Batra 355f6e9b53 settings: Move 'enter_sends' setting to property_types dict.
This commit moves "enter_sends" setting to property_types dict.
With this change, changing enter_sends setting also sends an
event of type "update_display_settings" and thus enables us
to live-update the UI.
2021-07-27 15:52:53 -07:00
Mateusz Mandera 013d6fa5e6 bots: Assume STAFF_SUBDOMAIN to be the realm where ERROR_BOT lives.
Now that get_system_bot requires a realm argument, a subdomain
needs to be made explicit to know in which organization to look up the
bot.
2021-07-27 15:51:59 -07:00
PIG208 e517f967b8 typing: Amend inaccurate type annotations.
This amend some type annotations that turn out to be inaccurate with
django-stubs.
2021-07-27 12:17:00 -07:00
Mateusz Mandera 8f588dcbab models: Pass realm to get_user_including_cross_realm calls. 2021-07-26 15:33:13 -07:00
Mateusz Mandera 43329b6a34 bots: Pass realm to get_system_bot calls in export/import. 2021-07-26 15:33:13 -07:00
Mateusz Mandera 7a36ac6eca bots: Pass realm to get_system_bot call in server_initialization.py. 2021-07-26 15:33:13 -07:00
Mateusz Mandera 0416f0385a bots: Pass realm to get_system_bot calls in onboarding.py. 2021-07-26 15:33:13 -07:00
Mateusz Mandera a124a4dfcf bots: Pass realm to get_system_bot calls in actions.py. 2021-07-26 15:33:13 -07:00
Mateusz Mandera 994ee70497 bots: Pass realm to self.notification_bot test helper. 2021-07-26 15:33:13 -07:00
Mateusz Mandera 104139657b bots: Pass realm to get_system_bot calls in email_mirror. 2021-07-26 15:33:13 -07:00
Mateusz Mandera d45f3eecaa models: Add optional realm_id argument to get_system_bot. 2021-07-26 15:31:10 -07:00
PIG208 d2af20eb2a typing: Do explicit type conversion when appropriate.
When calling some functions or assigning values to certain attributes,
the arguments/right operand do not match the exact type that the
functions/attributes expect, and thus we fix that by converting types
beforehand.
2021-07-26 15:09:07 -07:00
PIG208 7d1c475f69 typing: Use assertions for function arguments.
Utilize the assert_is_not_None helper to eliminate errors of
'Argument x to "Foo" has incompatible type "Optional[Bar]"...'
2021-07-26 14:48:45 -07:00
PIG208 2972e921b7 utils: Add a helper function for None-checks. 2021-07-26 14:46:45 -07:00
Dinesh 199f522808 test_classes.py: Replace markdown_logger mock with assertLogs.
Set level to 'ERROR' since exceptions create logs with that level.
2021-07-26 14:46:01 -07:00
Tim Abbott 09b5bb7930 export: Improve error message for missing registrations. 2021-07-24 17:36:15 -07:00
Mateusz Mandera 119f1da04a bots: Rename is_cross_realm_bot API field to is_system_bot.
Cross realm bots will soon stop being a thing. This param is responsible
for displaying "System Bot" in the user info popover - so this rename is the
right way to handle the situation.

We will likely want to rename the `cross_realm_bots` section as well,
but that is a more involved API migration.
2021-07-24 15:46:40 -07:00
PIG208 987f859681 webhooks: Detect view function with default naming convention. 2021-07-24 15:10:09 -07:00