Commit Graph

15476 Commits

Author SHA1 Message Date
Anders Kaseorg 751b2a03e5 CVE-2022-31168: Fix authorization check for changing bot roles.
Due to an incorrect authorization check in Zulip Server 5.4 and
earlier, a member of an organization could craft an API call that
grants organization administrator privileges to one of their bots.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2022-07-21 17:59:09 -07:00
Lauryn Menard ad2ca0e668 tests: Remove `FORWARD_ADDRESS_CONFIG_FILE` created in test.
Previously if `test_forward_address_details` failed, the file
created when setting the `forward_address` may not have been
removed, which would then cause an `EmailNotDeliveredException`
to be raised when then creating a new user in the dev environment.

Wraps the test in a try block, with a finally block for the call
to remove the file.
2022-07-21 15:25:11 -07:00
Mateusz Mandera f787ddc7d2 get_object_from_key: Make mark_object_used an obligatory kwarg. 2022-07-21 15:18:15 -07:00
Tim Abbott dcc03a453a confirmation: Tighten logic around the mark_object_used parameter. 2022-07-21 15:18:15 -07:00
Tim Abbott 495671cca0 confirmation: Rename confusing activate_object parameter. 2022-07-21 15:17:37 -07:00
Mateusz Mandera fa7700df11 confirmation: Rename STATUS_ACTIVE to STATUS_USED.
That's much more descriptive of what that value actually means about the
Confirmation objects.
2022-07-21 15:17:37 -07:00
Mateusz Mandera cd1e062878 registration: Return proper error page if a registration link is reused.
Before this, a link still couldn't be re-used because it would trip up
exception further down user creation codepaths, but that was still a
bug. check_prereg_key is supposed to correctly validate the key - and
trigger an error page being returned if a key (or for any other reason,
the attached PreregistrationUser object) is reused.

test_validate_email_not_already_in_realm needs to be adjusted, because
it was actually re-using a key.
2022-07-21 15:17:37 -07:00
Mateusz Mandera 328a1fcf13 test_signup: Fix typo in test name. 2022-07-21 15:17:37 -07:00
Tim Abbott 8faa854267 Revert "message_flags: Filter msgs having (or not) the flag before updating."
This reverts commit 40fcf5a633.

This commit triggers bug that we haven't fully tracked down, where web
app clients will continually send `update_message_flags` requests,
that then send out via the events system "0 messages were marked as
read" notices, eventually leading to a load spike.

The Tornado part can likely be fixed by checking if
updated_message_ids is empty, but we need to track down the frontend
bug as well.
2022-07-21 14:29:54 -07:00
Anders Kaseorg 443b974b3e python: Apply changes from pyupgrade.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2022-07-20 22:33:28 -07:00
Zixuan James Li 22ebf701aa cache: Use getattr to access _cache.
`_cache` is not an attribute defined on `BaseCache`, but an
implementation detail of django_bmemcache.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-20 22:00:05 -07:00
Lauryn Menard beb09cdf38 api-docs: Add warning formatting to important description notes.
Adds warning block formatting around important notes in the
`/get-events` and `/dev-fetch-api-key` endpoint documentation.
2022-07-20 14:36:15 -07:00
Lauryn Menard 6e924125ad api-docs: Remove include links in endpoint descriptions.
Two endpoints had linked markdown files that were used in
their general descriptions to add warning notes with important
information (`/create-user` and `/get-user-groups`).

This moves the warning content to be inline in the endpoint
descriptions so that the important content is in the OpenAPI
documentation and is still formatted to be rendered in a warning
block.

Deletes `can-create-users-only.md` and `api-members-only.md`
since they were only used for these two endpoint descriptions.

Also, cleans up the other instance of a inline warning block in
an endpoint description (`/fetch-api-key`).
2022-07-20 14:36:15 -07:00
Lauryn Menard 8a0070ace7 decorator: Move tornado notify `data` parameter to `REQ` framework.
Instead of using `request.POST` to access the `data` parameter used
in the internal `notify_tornado` path, adds `has_request_variables`
decorator and accesses `data` as a `REQ` parameter.

Expands `test_tornado_endpoint` in `test_event_system.py` for
`data` being a required parameter for this path.
2022-07-20 14:23:05 -07:00
Lauryn Menard 0301941eef email-log: Move `forward_address` to `REQ` framework.
Instead of using `request.POST` to access `forward_address` for
the parameter used in `set_forward_address` in `email_page`, adds
`has_request_variable` decorator and an optional `forward_address`
parameter through the `REQ` framework.

Adds an assertion that `forward_address` is not `None` for `POST`
requests.
2022-07-20 14:22:25 -07:00
Lauryn Menard 8ff948ba47 translation: Translate new user messages to realm's default language.
Previously, automated stream messages for new user signups were not
being translated into the realm's default language for said messages.

Moves `override_language` context manager so that it wraps the
new user message content in `notify_new_user` and topic string in
`send_message_to_signup_notification_stream`.

Fixes #22510.
2022-07-20 12:38:05 -07:00
Zixuan James Li 32af240af3 documentation: Make get compatible with the supertype.
The supertype contains `*args` and `**kwargs`, this adapts the signature
of the `get` method to make MarkdownDirectoryView compatible with it.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-19 17:48:27 -07:00
Zixuan James Li 5a15fd1dd2 documentation: Call TemplateView.get correctly.
The calling arguments here are completely wrong. The first argument
should be `request`, and `self` should never get passed to `.get`.

Because `TemplateView` happened to not use `request`, and we happened
to pass `article` as a keyword argument, this error slipped through.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-19 17:48:27 -07:00
Lauryn Menard eb2ee5605c api-docs: Update changelog and notes about GitLab authentication.
Updates changelog entry for feature level 1 about GitLab to include
the endpoint with the changes. Also noted that the change updated
a deprecated return value.

Added changes note to the `gitlab` boolean in the
`authentication_methods` return value for the
`/get-server-settings` endpoint.

Part of work on #22102.
2022-07-19 17:45:34 -07:00
Lauryn Menard edeacb63ff api-docs: Update changelog and notes about video call provider None.
Updates the changelog note in feature level 1 about adding None as
a video call provider to include the endpoints where this realm
setting is used.

Updates the OpenAPI doc for the realm setting `video_chat_provider`
to include information about the enum values and meanings.

Part of work on #22102.
2022-07-19 17:45:34 -07:00
Lauryn Menard ddd9cc3ec9 api_docs: Correct Zulip 3.0 feature level 1 changelog and notes.
Corrects omissions or inconsistencies between the api changelog
and the api documentation for Zulip 3.0, feature level 1,
except for the final two bullet points about GitLab authentication
and adding None as a video call provider option.

The final two bullet points will be addressed in separate commits.

Part of work on #22102.
2022-07-19 17:45:34 -07:00
Lauryn Menard c5ebb74280 api-docs: Fix errors found in audit of 3.0 changelog entries.
Initial round of fixes and clean-ups found during audit of
changelog entries for feature levels 1-27, which correspond
to the 3.0 release.

There are a few changes that are not related to those feature
levels, but fit within the context of clean-ups (spelling mistakes
or errors in api documentation formatting/structure/style).

One notable non-3.0 release fix is making all changes notes in
the OpenAPI documentation for 2.x releases use the correct
version numbering-scheme for those releases (e.g. 2.0.0).

Follow-up commits / PRs will address inconsitencies and omissions
for these feature levels found during the audit.
2022-07-19 17:45:34 -07:00
ritikBhandari 861ddea1cd help-docs: Remove no longer accurate "notifications" terminology.
Updates references / language about organization settings that
were previously labeled as "Notifications", but are now labeled
as "Automated messages and emails".

Fixes #22136.

Co-authored by: Lauryn Menard <lauryn@zulip.com>
2022-07-19 17:32:47 -07:00
Zixuan James Li cd8510607a queue_processor: Remove unreachable code.
This change was added in
c93f1d4eda (diff-d88010b113b79080cab5885fdfbbb56ae2d380cb601d8f520621b3361ad8cebc).
`message.content` cannot be `None` by the model definition.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-19 17:30:15 -07:00
Alex Vandiver 102481bc47 migrations: Adjust stats size for tsvector to 10k, from 100.
PostgreSQL's `default_statistics_target` is used to track how many
"most common values" ("MCVs") for a column when performing an
`ANALYZE`.  For `tsvector` columns, the number of values is actually
10x this number, because each row contains multiple values for the
column[1].  The `default_statistics_target` defaults to 100[2], and
Zulip does not adjust this at the server level.

This translates to 1000 entries in the MCV for tsvectors. For
large tables like `zerver_messages`, a too-small value can cause
mis-planned query plans.  The query planner assumes that any
entry *not* found in the MCV list is *half* as likely as the
least-likely value in it.  If the table is large, and the MCV list is
too short (as 1000 values is for large deployments), arbitrary
no-in-the-MCV words will often be estimated by the query planner to
occur comparatively quite frequently in the index.  Based on this, the
planner will instead choose to scan all messages accessible by the
user, filtering by word in tsvector, instead of using the tsvector
index and filtering by being accessible to the user.  This results in
degraded performance for word searching.

However, PostgreSQL allows adjustment of this value on a per-column
basis.  Add a migration to adjust the value up to 10k for
`search_tsvector` on `zerver_message`, which results in 100k entries
in that MCV list.

PostgreSQL's documentation says[3]:

> Raising the limit might allow more accurate planner estimates to be
> made, particularly for columns with irregular data distributions, at
> the price of consuming more space in `pg_statistic` and slightly
> more time to compute the estimates.

These costs seem adequate for the utility of having better search.
In the event that the pgroonga backend is in use, these larger index
statistics are simply wasted space and `VACUUM` computational time,
but the costs are likely still reasonable -- even 100k values are
dwarfed by the size of the database needed to generate 100k unique
entries in tsvectors.

[1]: https://github.com/postgres/postgres/blob/REL_14_4/src/backend/utils/adt/array_typanalyze.c#L261-L267
[2]: https://www.postgresql.org/docs/14/runtime-config-query.html#GUC-DEFAULT-STATISTICS-TARGET
[3]: https://www.postgresql.org/docs/14/planner-stats.html#id-1.5.13.5.3
2022-07-19 09:24:06 -07:00
Zixuan James Li 159449b448 response: Replace json_unauthorized with UnauthorizedError.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-18 18:01:42 -07:00
Zixuan James Li 31c7344979 test_message_fetch: Verify the value of WWW-Authenticate.
In `JsonableErrorHandler`, we convert `MissingAuthenticationError` into
a response that has `WWW-Authenticated` set for `/api` or `/json` views.

This covers and verify the value of the header for unauthenticated
access.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-18 18:01:42 -07:00
Mateusz Mandera ff01777139 create_user: Improve comment about prereg_user handling.
The dangling comment was not very helpful and unclear about the pieces
of code it was referring to.

We expand the part about linking the prereg_user to the created user,
while the part about "revoking other preregistration users" is
redundant, because the relevant code block lower down already has
comments on it with better explanations.
2022-07-18 12:16:20 -07:00
Mateusz Mandera 6b451ce6f0 create_user: Remove assert about needing prereg_user if realm_creation.
Closes #22274.

This assertion was added in 4b903c5dcd
where it may have made sense, because indeed when doing realm creation
there was always a PreregistrationUser (created because realms were
created via going to a generated realm creation link). With the addition
of the create_realm command that's no longer the case.

It would be unnatural to create a PreregistrationUser in the
realm_creation command, because there is no confirmation link for it to
be tied to - and it just doesn't make sense conceptually.

The intended, correct behavior added in
4b903c5dcd is still maintained - the code
lower down correctly handles the
(prereg_user is None and realm_creation) case.
2022-07-18 12:16:20 -07:00
Anders Kaseorg 7d8be670a5 message_send: Remove TypeGuard.
The type safety of a TypeGuard is unchecked by mypy.  While this
particular TypeGuard is safe given the current context, one could
imagine future changes that make it unsafe, so it’s preferable to
avoid unchecked constructs whenever possible.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2022-07-16 10:44:16 -07:00
Sahil Batra 690420ffa0 populate_db: Fix data for "Favorite editor" custom field.
The field_data sent from client while creating a select
type field is a dict with a number as key.

In development database the field data for "Favorite editor"
field was of different form where the option label was used
as key in the dict.

This commit fixes it to be of the same as it is when creating
a field from web-app. As a result, we also need to update
the tests and this commit also update field_data for other
select-type fields.
2022-07-15 16:51:24 -07:00
Sahil Batra 0afda70c3f migration: Add migration to remove user values for deleted options.
This commit adds migration to delete CustomProfileFieldValue
objects for deleted options of SELECT type custom profile
fields.
2022-07-15 16:51:22 -07:00
Sahil Batra fac5e0605b custom_profile_fields: Delete invalid values for select-type fields.
We delete the user values for options which were deleted for the
field.
2022-07-15 16:33:15 -07:00
Zixuan James Li 4099e56a1f custom_profile: Refactor test_update_profile_data_successfully.
This refactors the test case with more explicit type annotations, fixing
type errors discovered provided type annotations for
`CustomProfileField`.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:55:03 -07:00
Zixuan James Li 52be020d0c custom_profile: Apply ProfileDataElementUpdateDict.
We explicitly annotate variables or parameters with
`ProfileDataElementUpdateDict` as necessary.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:55:03 -07:00
Zixuan James Li 5116efa3de users: Tighten the type annotation of clean_profile_data.
This change ensures that we can call the validate and update helper for
custom profile data later.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:55:03 -07:00
Zixuan James Li 00f2040ffa custom_profile: Use cast to ensure ProfieDataElementUpdateDict.
We refactor the validator of `update_user_custom_profile_data` to ensure
that the validated variable is properly typed as
a `ProfileDataElementUpdateDict`, so we can call
`validate_user_custom_profile_data` and
`do_update_user_custom_profile_data_if_changed` directly later (unlike
`update_user_backend`, where `value` is allowed to be `None`, the
validator already ensures that no further check is required).
2022-07-15 14:55:03 -07:00
Zixuan James Li c7f75f071e types: Add ProfileDataElementUpdateDict.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:55:03 -07:00
Zixuan James Li b210c22329 message_send: Extract ActiveUserDict for accurate typing.
django-stubs types the return type of query.values(...) as a TypedDict.
This makes Dict[str, Any] that we have been using incompatible with it.

We use TypeGuard to ensure that `service_bot_tuples` is correctly
inferred to be `Tuple[int, int]` instead of `Tuple[int, Optional[int]]`.
Given that `bot_type` is optional for `ActiveUserDict`, we need to
narrow `row` to `ActiveBotUserDict` to make sure that `bot_type` is
non-optional. An advantage of this approach is that no assertions or
type casts are needed.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:02:40 -07:00
Zixuan James Li 0bedf0cf22 integrations: Fix wrong type annotation.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li db7a6d15dc test_auth_backends: Replace handcrafted requests with HostRequestMock.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li 56855e0187 typing: Add assertions for Optional values.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li 7c62af0d73 typing: Add assertions before accessing settings.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li a09c9a4063 test_auth_backends: Remove unused return.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li 0ef5eee3f0 error_notify: Fix type narrowing of settings.ERROR_BOT.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li c5075be9aa test_retention: Add type annotation for expected_result
Otherwise mypy infers the type of `expected_result` to be incompatible
with the first argument of `fix_ordering_of_result`.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li e665ec8ae2 middleware: Add isinstance check before retrieving content.
StreamingHttpResponse is inferred without the isinstance check in the
else branch. We refactor this is shorten the code and also type narrow
it appropriately.
2022-07-15 14:00:56 -07:00
Zixuan James Li 2095258aa5 middleware: Assert request.method is not None.
`request.method` is not `None` in normal use cases, unless an
`HttpRequest` is directly instantiated without the method being set.
This situation does not apply to `WSGIRequest` at all.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li ece3fbdf95 migrations: Use the correct type annotation for the Model type.
Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00
Zixuan James Li 7d86d291d4 middleware: Remove inappropriate StreamingHttpResponse annotation.
Asserting response.stream is False is just suggesting the response being
an `HttpResponse`. This removes `StreamingHttpResponse` with the more
generic `HttpResponseBase` with an isinstance-check.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
2022-07-15 14:00:56 -07:00