Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
realm_export: Use string enum instead of int for export_type.
Shubham Padia7f6b7d22b1a4
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 017d494d7ab..43b7d50bbd4 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,19 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 449**++* [`POST /export/realm`](/api/export-realm): The `export_type` parameter now+ takes string values (`public`, `full_with_consent`, `full_without_consent`)+ instead of integers. The new `full_without_consent` option requests a full+ export that includes private data for all users and requires the organization+ to have the `owner_full_content_access` flag set to True.+* [`GET /export/realm`](/api/get-realm-exports), [`GET /events`](/api/get-events):+ `export_type` fields now contain the new string values, matching the+ `POST /export/realm` parameter format. These endpoints now report+ `export_type=full_without_consent` for a full export that includes private data+ for all users.+**Feature level 448*** [`GET /streams/{stream_id}/email_address`](/api/get-stream-email-address):diff --git a/api_docs/unmerged.d/ZF-712cf1.md b/api_docs/unmerged.d/ZF-712cf1.mddeleted file mode 100644index 83254e5343a..00000000000--- a/api_docs/unmerged.d/ZF-712cf1.md+++ /dev/null@@ -1,7 +0,0 @@-* [`POST /export/realm`](/api/export-realm): Added support for- `export_type=3`, which requests a full export that includes private data for- all users. This option requires the organization to have the- `owner_full_content_access` flag set to True.-* [`GET /export/realm`](/api/get-realm-exports), [`GET /events`](/api/get-events):- These endpoints now report `export_type=3` for a full export that includes- private data for all users.diff --git a/version.py b/version.pyindex ded3f7afd27..cb2c90e5728 100644--- a/version.py+++ b/version.py@@ -35,7 +35,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# new level means in api_docs/changelog.md, as well as "**Changes**"# entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 448+API_FEATURE_LEVEL = 449# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/web/src/settings_config.ts b/web/src/settings_config.tsindex 86988c7460e..8cc5f3ad99f 100644--- a/web/src/settings_config.ts+++ b/web/src/settings_config.ts@@ -1331,27 +1331,27 @@ export const stream_privacy_policy_values = {},};+export type ExportTypeSlug = "public" | "full_with_consent" | "full_without_consent";+export type ExportTypeOption = {- value: number;+ slug: ExportTypeSlug;description: string;default: boolean;};-export type ExportTypeSlug = "public" | "full_with_consent" | "full_without_consent";-export const export_type_values: Record<ExportTypeSlug, ExportTypeOption> = {public: {- value: 1,- description: $t({defaultMessage: "Public data only"}),+ slug: "public",+ description: $t({defaultMessage: "Public data"}),default: false,},full_with_consent: {- value: 2,+ slug: "full_with_consent",description: $t({defaultMessage: "Public and private data (with consent)"}),default: true,},full_without_consent: {- value: 3,+ slug: "full_without_consent",description: $t({defaultMessage: "All public and private data"}),default: false,},diff --git a/web/src/settings_exports.ts b/web/src/settings_exports.tsindex adc754482dd..f2b55647455 100644--- a/web/src/settings_exports.ts+++ b/web/src/settings_exports.ts@@ -36,6 +36,12 @@ export const export_consent_schema = z.object({});type ExportConsent = z.output<typeof export_consent_schema>;+const realm_export_type_schema = z.enum([+ settings_config.export_type_values.public.slug,+ settings_config.export_type_values.full_with_consent.slug,+ settings_config.export_type_values.full_without_consent.slug,+]);+export const realm_export_schema = z.object({id: z.number(),export_time: z.number(),@@ -44,7 +50,7 @@ export const realm_export_schema = z.object({deleted_timestamp: z.nullable(z.number()),failed_timestamp: z.nullable(z.number()),pending: z.boolean(),- export_type: z.number(),+ export_type: realm_export_type_schema,});type RealmExport = z.output<typeof realm_export_schema>;@@ -60,6 +66,12 @@ function get_export_type_options_to_render(): settings_config.ExportTypeOption[]return [settings_config.export_type_values.public, standard_option];}+function get_export_type_from_select(+ $export_type: JQuery<HTMLSelectOneElement>,+): settings_config.ExportTypeSlug {+ return realm_export_type_schema.parse($export_type.val());+}+let users_consented_for_export_count: number;let total_users_count: number;@@ -103,14 +115,6 @@ export function populate_exports_table(exports: RealmExport[]): void {);}- let export_type_description = settings_config.export_type_values.public.description;- const export_type_value = Object.values(settings_config.export_type_values).find(- (element) => element.value === data.export_type,- );- if (export_type_value) {- export_type_description = export_type_value.description;- }-return render_admin_export_list({realm_export: {id: data.id,@@ -123,7 +127,8 @@ export function populate_exports_table(exports: RealmExport[]): void {time_failed: failed_timestamp,pending: data.pending,time_deleted: deleted_timestamp,- export_type_description,+ export_type_description:+ settings_config.export_type_values[data.export_type].description,},});},@@ -320,14 +325,16 @@ export function refresh_allow_private_data_export_banner(): void {} else if ($("#allow_private_data_export_banner_container").length > 0) {maybe_show_allow_private_data_export_banner();const $export_type = $<HTMLSelectOneElement>("select:not([multiple])#export_type");- const selected_export_type = Number.parseInt($export_type.val()!, 10);- if (selected_export_type === settings_config.export_type_values.public.value) {+ const selected_export_type = get_export_type_from_select($export_type);+ if (selected_export_type === settings_config.export_type_values.public.slug) {$(".allow_private_data_export_warning").hide();}}}-function maybe_show_notes_about_unusable_users_if_exported(export_type: number): void {+function maybe_show_notes_about_unusable_users_if_exported(+ export_type: settings_config.ExportTypeSlug,+): void {// Show warnings if there are users whose accounts will be inaccessible// once exported. A user account will be inaccessible if they:// - Don’t consent to their private data being exported and “Standard@@ -337,10 +344,10 @@ function maybe_show_notes_about_unusable_users_if_exported(export_type: number):let unusable_user_ids: number[] = [];const $warning_container = $("div#unusable-user-accounts-warning");$warning_container.empty();- if (export_type === settings_config.export_type_values.full_with_consent.value) {+ if (export_type === settings_config.export_type_values.full_with_consent.slug) {const non_consenting_users = get_export_consents_having_consent_value(false);unusable_user_ids = non_consenting_users.map((user) => user.user_id);- } else if (export_type === settings_config.export_type_values.public.value) {+ } else if (export_type === settings_config.export_type_values.public.slug) {const users_with_inaccessible_email = get_export_consents_having_email_visibility_value(settings_config.email_address_visibility_values.nobody.code,);@@ -379,9 +386,8 @@ function show_start_export_modal(): void {function start_export(): void {dialog_widget.show_dialog_spinner();const $export_status = $("#export_status");- const export_type = Number.parseInt(- $<HTMLSelectOneElement>("select:not([multiple])#export_type").val()!,- 10,+ const export_type = get_export_type_from_select(+ $<HTMLSelectOneElement>("select:not([multiple])#export_type"),);void channel.post({@@ -422,9 +428,9 @@ function show_start_export_modal(): void {const $export_type = $<HTMLSelectOneElement>("select:not([multiple])#export_type");$export_type.on("change", () => {- const selected_export_type = Number.parseInt($export_type.val()!, 10);+ const selected_export_type = get_export_type_from_select($export_type);if (- selected_export_type === settings_config.export_type_values.full_with_consent.value+ selected_export_type === settings_config.export_type_values.full_with_consent.slug) {$("#allow_private_data_export_stats").show();$(".allow_private_data_export_warning").show();diff --git a/web/templates/start_export_modal.hbs b/web/templates/start_export_modal.hbsindex dca446b594e..e95cb54fb80 100644--- a/web/templates/start_export_modal.hbs+++ b/web/templates/start_export_modal.hbs@@ -4,7 +4,7 @@<label for="export_type" class="modal-field-label">{{t "Data to export" }} {{> help_link_widget link="/help/export-your-organization" }}</label><select id="export_type" class="modal_select bootstrap-focus-style">{{#each export_type_values}}- <option {{#if this.default }}selected{{/if}} value="{{this.value}}">{{this.description}}</option>+ <option {{#if this.default }}selected{{/if}} value="{{this.slug}}">{{this.description}}</option>{{/each}}</select></div>diff --git a/web/tests/lib/events.cjs b/web/tests/lib/events.cjsindex 8e6acc93d1c..96b224f9f05 100644--- a/web/tests/lib/events.cjs+++ b/web/tests/lib/events.cjs@@ -611,7 +611,7 @@ exports.fixtures = {deleted_timestamp: null,failed_timestamp: null,pending: true,- export_type: 1,+ export_type: "public",},],},diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.pyindex f4bba99af9b..7350c6cd2d7 100644--- a/zerver/lib/event_types.py+++ b/zerver/lib/event_types.py@@ -5,6 +5,7 @@ from django.core.validators import URLValidatorfrom pydantic import AfterValidator, BaseModelfrom zerver.lib.types import UserGroupMembersDict+from zerver.models.realms import RealmExportSlugdef check_url(val: str) -> str:@@ -509,7 +510,7 @@ class Export(BaseModel):deleted_timestamp: float | int | Nonefailed_timestamp: float | int | Nonepending: bool- export_type: int+ export_type: RealmExportSlugclass EventRealmExport(BaseEvent):diff --git a/zerver/lib/export.py b/zerver/lib/export.pyindex 6ee41b5854e..96ce7b443a1 100644--- a/zerver/lib/export.py+++ b/zerver/lib/export.py@@ -92,7 +92,7 @@ from zerver.models import (from zerver.models.messages import SubMessagefrom zerver.models.presence import PresenceSequencefrom zerver.models.realm_audit_logs import AuditLogEventType-from zerver.models.realms import get_fake_email_domain, get_realm+from zerver.models.realms import DEFAULT_REALM_EXPORT_TYPE_SLUG, get_fake_email_domain, get_realmfrom zerver.models.saved_snippets import SavedSnippetfrom zerver.models.users import ExternalAuthID, get_system_bot, is_cross_realm_bot_email@@ -3116,6 +3116,15 @@ def export_realm_wrapper(raise+def get_export_type_slug(export_type: int) -> str:+ result = DEFAULT_REALM_EXPORT_TYPE_SLUG+ for export_type_slug, export_type_value in RealmExport.EXPORT_TYPES.items():+ if export_type == export_type_value:+ result = export_type_slug++ return result++def get_realm_exports_serialized(realm: Realm) -> list[dict[str, Any]]:# Exclude exports made via shell. 'acting_user=None', since they# aren't supported in the current API format.@@ -3148,7 +3157,7 @@ def get_realm_exports_serialized(realm: Realm) -> list[dict[str, Any]]:deleted_timestamp=deleted_timestamp,failed_timestamp=failed_timestamp,pending=pending,- export_type=export.type,+ export_type=get_export_type_slug(export.type),)return sorted(exports_dict.values(), key=lambda export_dict: export_dict["id"])diff --git a/zerver/models/realms.py b/zerver/models/realms.pyindex 79e88b7071c..4ce6126b925 100644--- a/zerver/models/realms.py+++ b/zerver/models/realms.py@@ -1,7 +1,7 @@from email.headerregistry import Addressfrom enum import Enum, IntEnumfrom types import UnionType-from typing import TYPE_CHECKING, Optional, TypedDict+from typing import TYPE_CHECKING, Literal, Optional, TypedDictfrom uuid import uuid4import django.contrib.auth@@ -30,6 +30,8 @@ if TYPE_CHECKING:SECONDS_PER_DAY = 86400+RealmExportSlug = Literal["public", "full_with_consent", "full_without_consent"]+DEFAULT_REALM_EXPORT_TYPE_SLUG: RealmExportSlug = "public"# This simple call-once caching saves ~500us in auth_enabled_helper,@@ -1407,11 +1409,11 @@ class RealmExport(models.Model):EXPORT_PUBLIC = 1EXPORT_FULL_WITH_CONSENT = 2EXPORT_FULL_WITHOUT_CONSENT = 3- EXPORT_TYPES = [- EXPORT_PUBLIC,- EXPORT_FULL_WITH_CONSENT,- EXPORT_FULL_WITHOUT_CONSENT,- ]+ EXPORT_TYPES: dict[RealmExportSlug, int] = {+ "public": EXPORT_PUBLIC,+ "full_with_consent": EXPORT_FULL_WITH_CONSENT,+ "full_without_consent": EXPORT_FULL_WITHOUT_CONSENT,+ }type = models.PositiveSmallIntegerField(default=EXPORT_PUBLIC)REQUESTED = 1diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex db7c64e9986..7af39599b3e 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -4172,7 +4172,7 @@ paths:"deleted_timestamp": null,"failed_timestamp": 1594825444.4363360405,"pending": false,- "export_type": 1,+ "export_type": "public",},],"id": 1,@@ -15481,7 +15481,7 @@ paths:{"acting_user_id": 11,"deleted_timestamp": null,- "export_type": 1,+ "export_type": "public","export_time": 1722243168.134179,"export_url": "http://example.zulipchat.com/user_avatars/exports/2/FprbwiF0c_sCN0O-rf-ryFtc/zulip-export-p6yuxc45.tar.gz","id": 323,@@ -15526,27 +15526,29 @@ paths:Whether the data export should be public, full with consent,or full without consent.- - 1 = Public data only export.- - 2 = Public and private data export (with consent), which includes+ - `public` = Public data only export.+ - `full_with_consent` = Public and private data export (with consent), which includesprivate data for users who have granted consent.- - 3 = All public and private data export, which includes private data for+ - `full_without_consent` = All public and private data export, which includes private data forall users. This option requires the organization to havethe `owner_full_content_access` feature enabled.- If not specified, defaults to 1.+ If not specified, defaults to `public`.- **Changes**: Zulip 12.0 (feature level ZF-712cf1) added the value 3- option for data export of all public and private data.+ **Changes**: Zulip 12.0 (feature level 449) changed the type of+ this field from int to string with `1` being replaced by `public` and+ `2` being replaced by `full_with_consent`. The option `full_without_consent`+ was added for full exports without member consent.**Changes**: New in Zulip 10.0 (feature level 304). Previously,all export requests were public data exports.- type: integer+ type: stringenum:- - 1- - 2- - 3- default: 1- example: 2+ - public+ - full_with_consent+ - full_without_consent+ default: public+ example: full_with_consentresponses:"200":description: Success@@ -26045,17 +26047,23 @@ components:anywhere from seconds to an hour to generate the dataexport.export_type:- type: integer+ type: string+ enum:+ - public+ - full_with_consent+ - full_without_consentdescription: |Whether the data export is public, full with consent, or full without consent.- - 1 = Public data only export.- - 2 = Public and private data export (with consent), which includes private data+ - `public` = Public data export.+ - `full_with_consent` = Public and private data export (with consent), which includes private datafor users who have granted consent.- - 3 = All public and private data, which includes private data for all users.+ - `full_without_consent` = All public and private data, which includes private data for all users.- **Changes**: Zulip 12.0 (feature level ZF-712cf1) added the value 3 option- for data export of all public and private data.+ **Changes**: Zulip 12.0 (feature level 449) changed the type of+ this field from int to string with `1` being replaced by `public` and+ `2` being replaced by `full_with_consent`. The option `full_without_consent`+ was added for full exports without member consent.**Changes**: New in Zulip 10.0 (feature level 304). Previously,the export type was not included in these objects because onlydiff --git a/zerver/tests/test_realm_export.py b/zerver/tests/test_realm_export.pyindex 50cb1536fd7..610294fff1b 100644--- a/zerver/tests/test_realm_export.py+++ b/zerver/tests/test_realm_export.py@@ -20,6 +20,7 @@ from zerver.lib.test_helpers import (use_s3_backend,)from zerver.models import Realm, RealmExport, UserProfile+from zerver.models.realms import RealmExportSlugfrom zerver.views.realm_export import export_realm@@ -363,7 +364,14 @@ class RealmExportTest(ZulipTestCase):continueself.assertFalse(export_consent["consented"])- def check_success_realm_export(self, acting_user: UserProfile, export_type: int) -> None:+ PUBLIC_EXPORT_TYPE: RealmExportSlug = "public"+ FULL_WITH_CONSENT_EXPORT_TYPE: RealmExportSlug = "full_with_consent"+ FULL_WITHOUT_CONSENT_EXPORT_TYPE: RealmExportSlug = "full_without_consent"++ def check_success_realm_export(+ self, acting_user: UserProfile, export_type: RealmExportSlug+ ) -> None:+ expected_realm_export_type = RealmExport.EXPORT_TYPES[export_type]with patch("zerver.views.realm_export.queue_event_on_commit") as mock_event_on_commit:result = self.client_post("/json/export/realm",@@ -381,7 +389,7 @@ class RealmExportTest(ZulipTestCase):}mock_event_on_commit.assert_called_once_with("deferred_work", expected_event)realm_export = RealmExport.objects.get(id=realm_export_id)- self.assertEqual(realm_export.type, export_type)+ self.assertEqual(realm_export.type, expected_realm_export_type)def test_allow_export_with_no_usable_user_accounts(self) -> None:"""@@ -398,7 +406,7 @@ class RealmExportTest(ZulipTestCase):).update(allow_private_data_export=False,)- self.check_success_realm_export(admin, RealmExport.EXPORT_FULL_WITH_CONSENT)+ self.check_success_realm_export(admin, self.FULL_WITH_CONSENT_EXPORT_TYPE)# For public export, this means everyone has set their email# address visibility policy to nobody.@@ -409,7 +417,7 @@ class RealmExportTest(ZulipTestCase):email_address_visibility=UserProfile.EMAIL_ADDRESS_VISIBILITY_NOBODY,)- self.check_success_realm_export(admin, RealmExport.EXPORT_PUBLIC)+ self.check_success_realm_export(admin, self.PUBLIC_EXPORT_TYPE)def test_full_without_consent_export_requires_org_permission(self) -> None:admin = self.example_user("iago")@@ -421,7 +429,7 @@ class RealmExportTest(ZulipTestCase):result = self.client_post("/json/export/realm",{- "export_type": RealmExport.EXPORT_FULL_WITHOUT_CONSENT,+ "export_type": self.FULL_WITHOUT_CONSENT_EXPORT_TYPE,},)self.assert_json_error(@@ -434,10 +442,10 @@ class RealmExportTest(ZulipTestCase):result = self.client_post("/json/export/realm",{- "export_type": RealmExport.EXPORT_FULL_WITHOUT_CONSENT,+ "export_type": self.FULL_WITHOUT_CONSENT_EXPORT_TYPE,},)self.assert_json_error(result, "Must be an organization owner")self.login_user(owner)- self.check_success_realm_export(owner, RealmExport.EXPORT_FULL_WITHOUT_CONSENT)+ self.check_success_realm_export(owner, self.FULL_WITHOUT_CONSENT_EXPORT_TYPE)diff --git a/zerver/views/realm_export.py b/zerver/views/realm_export.pyindex 9eb39fb79b8..fa8de4e56eb 100644--- a/zerver/views/realm_export.py+++ b/zerver/views/realm_export.py@@ -5,7 +5,6 @@ from django.db import transactionfrom django.http import HttpRequest, HttpResponsefrom django.utils.timezone import now as timezone_nowfrom django.utils.translation import gettext as _-from pydantic import Jsonfrom analytics.models import RealmCountfrom zerver.actions.realm_export import do_delete_realm_export, notify_realm_export@@ -16,8 +15,9 @@ from zerver.lib.queue import queue_event_on_commitfrom zerver.lib.response import json_successfrom zerver.lib.send_email import FromAddressfrom zerver.lib.typed_endpoint import typed_endpoint-from zerver.lib.typed_endpoint_validators import check_int_in_validator+from zerver.lib.typed_endpoint_validators import check_string_in_validatorfrom zerver.models import RealmExport, UserProfile+from zerver.models.realms import DEFAULT_REALM_EXPORT_TYPE_SLUG, RealmExportSlug@transaction.atomic(durable=True)@@ -27,24 +27,17 @@ def export_realm(request: HttpRequest,user: UserProfile,*,- export_type: Json[- Annotated[- int,- check_int_in_validator(- [- RealmExport.EXPORT_PUBLIC,- RealmExport.EXPORT_FULL_WITH_CONSENT,- RealmExport.EXPORT_FULL_WITHOUT_CONSENT,- ]- ),- ]- ] = RealmExport.EXPORT_PUBLIC,+ export_type: Annotated[+ RealmExportSlug,+ check_string_in_validator(RealmExport.EXPORT_TYPES.keys()),+ ] = DEFAULT_REALM_EXPORT_TYPE_SLUG,) -> HttpResponse:realm = user.realmEXPORT_LIMIT = 5+ export_type_value = RealmExport.EXPORT_TYPES[export_type]if (- export_type == RealmExport.EXPORT_FULL_WITHOUT_CONSENT+ export_type_value == RealmExport.EXPORT_FULL_WITHOUT_CONSENTand not realm.owner_full_content_access):raise JsonableError(@@ -52,7 +45,7 @@ def export_realm()if (- export_type == RealmExport.EXPORT_FULL_WITHOUT_CONSENT+ export_type_value == RealmExport.EXPORT_FULL_WITHOUT_CONSENTand realm.owner_full_content_accessand not user.is_realm_owner):@@ -87,7 +80,7 @@ def export_realm(realm_count_query = RealmCount.objects.filter(realm=realm, property="messages_sent:message_type:day")- if export_type == RealmExport.EXPORT_PUBLIC:+ if export_type_value == RealmExport.EXPORT_PUBLIC:realm_count_query.filter(subgroup="public_stream")exportable_messages_estimate = sum(realm_count.value for realm_count in realm_count_query)@@ -105,7 +98,7 @@ def export_realm(row = RealmExport.objects.create(realm=realm,- type=export_type,+ type=export_type_value,acting_user=user,status=RealmExport.REQUESTED,date_requested=timezone_now(),