Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
bots: Allow admins/owners to change bot short_name.
saiyam021147f9e88e591d
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex 3c09bdfe630..948a6112c19 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,10 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 447**++* `PATCH /bots/{bot_id}`: Added `short_name` parameter to support updating bot's email.+**Feature level 446*** [`GET /messages`](/api/get-messages),diff --git a/version.py b/version.pyindex b52b7acc216..4d3a1e353ee 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 = 446+API_FEATURE_LEVEL = 447# 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/user_profile.ts b/web/src/user_profile.tsindex 98c0bc2cc45..b5b447309af 100644--- a/web/src/user_profile.ts+++ b/web/src/user_profile.ts@@ -840,11 +840,14 @@ export function show_edit_bot_info_modal(user_id: number, $container: JQuery): vconst is_active = people.is_person_active(user_id);assert(bot.is_bot);+ // Extract short_name from email (format: {short_name}-bot@domain)+ const short_name = bot.email.split("@")[0]!.slice(0, -4);const html_body = render_edit_bot_form({user_id,is_active,is_bot_owner_current_user,email: bot.email,+ short_name,full_name: bot.full_name,user_role_values: settings_config.user_role_values,disable_role_dropdown: !current_user.is_admin || (bot.is_owner && !current_user.is_owner),@@ -853,6 +856,7 @@ export function show_edit_bot_info_modal(user_id: number, $container: JQuery): vapi_key: bot_user.api_key,is_incoming_webhook_bot: bot.bot_type === INCOMING_WEBHOOK_BOT_TYPE,max_bot_name_length: people.MAX_USER_NAME_LENGTH,+ realm_bot_domain: realm.realm_bot_domain,zuliprc: "zuliprc",});$container.append($(html_body));@@ -879,6 +883,10 @@ export function show_edit_bot_info_modal(user_id: number, $container: JQuery): voriginal_values = get_current_values($("#bot-edit-form"));$("#bot-edit-form").on("input", "input, select, button", (e) => {e.preventDefault();+ // Clear invalid state when user starts typing+ if ($(e.target).hasClass("invalid")) {+ $(e.target).removeClass("invalid");+ }toggle_submit_button($("#bot-edit-form"));});$("#user-profile-modal").on("click", ".dialog_submit_button", () => {@@ -887,6 +895,17 @@ export function show_edit_bot_info_modal(user_id: number, $container: JQuery): v10,);const $full_name = $("#bot-edit-form").find<HTMLInputElement>("input[name='full_name']");+ const $short_name = $("#bot-edit-form").find<HTMLInputElement>(+ "input[name='bot_short_name']",+ );++ const short_name_value = $short_name.val()!.trim();+ if (!bot_helper.validate_bot_short_name(short_name_value)) {+ $short_name.addClass("invalid");+ $short_name.trigger("focus");+ return;+ }+const url = "/json/bots/" + encodeURIComponent(bot.user_id);const formData = new FormData();@@ -894,6 +913,7 @@ export function show_edit_bot_info_modal(user_id: number, $container: JQuery): vformData.append("csrfmiddlewaretoken", csrf_token);formData.append("full_name", $full_name.val()!);formData.append("role", JSON.stringify(role));+ formData.append("short_name", short_name_value);const new_bot_owner_id = bot_owner_dropdown_widget!.value();if (new_bot_owner_id) {formData.append("bot_owner_id", new_bot_owner_id.toString());@@ -1132,12 +1152,22 @@ function toggle_submit_button($edit_form: JQuery): void {const current_values = get_current_values($edit_form);const $submit_button = $("#user-profile-modal .dialog_submit_button");const full_name_value = $edit_form.find<HTMLInputElement>("input[name='full_name']").val()!;+ const $short_name = $edit_form.find<HTMLInputElement>("input[name='bot_short_name']");if (full_name_value.trim() === "") {$submit_button.prop("disabled", true);return;}+ // Only check short_name for bot profiles+ if ($short_name.length > 0) {+ const short_name_value = $short_name.val()!.trim();+ if (short_name_value === "") {+ $submit_button.prop("disabled", true);+ return;+ }+ }+if (_.isEqual(original_values, current_values)) {$submit_button.prop("disabled", true);return;diff --git a/web/styles/modal.css b/web/styles/modal.cssindex 4451c799787..c18c1767721 100644--- a/web/styles/modal.css+++ b/web/styles/modal.css@@ -652,12 +652,23 @@}}-#create_bot_short_name {+#create_bot_short_name,+#edit_bot_short_name {/* A shorter dropdown width (~200px at 14px em)to ensure the email all fits on one line. */width: 14em;}+#edit_bot_short_name.invalid {+ border-color: var(--color-invalid-input-border);+ box-shadow: var(--invalid-input-box-shadow);+}++.email_change_container .settings-field-hint {+ color: var(--color-text-settings-field-hint);+ font-size: 0.9em;+}+#add-poll-modal,#add-todo-modal {/* this height allows 3-4 option rowsdiff --git a/web/templates/settings/edit_bot_form.hbs b/web/templates/settings/edit_bot_form.hbsindex c3b91e9cc9f..713101cf6ea 100644--- a/web/templates/settings/edit_bot_form.hbs+++ b/web/templates/settings/edit_bot_form.hbs@@ -7,8 +7,17 @@</div><input type="hidden" name="is_full_name" value="true" /><div class="input-group email_change_container">- <label for="email" class="modal-field-label">{{t "Email" }}</label>- <input type="text" autocomplete="off" name="email" class="modal_text_input" value="{{ email }}" readonly/>+ <label for="edit_bot_short_name" class="modal-field-label">+ {{t "Bot email (a-z, 0-9, and dashes only)" }}+ {{> ../help_link_widget link="/help/bots-overview" }}+ </label>+ <input type="text" autocomplete="off" name="bot_short_name" id="edit_bot_short_name"+ class="modal_text_input"+ value="{{ short_name }}" placeholder="{{t 'cookie' }}" maxlength="100" />+ -bot@{{ realm_bot_domain }}+ <div class="settings-field-hint">+ {{t "Integrations will need to be updated to use the new email address." }}+ </div></div><div class="input-group user_id_container"><label for="user_id" class="modal-field-label">{{t "User ID" }}</label>diff --git a/zerver/tests/test_bots.py b/zerver/tests/test_bots.pyindex 7d19dc7b60f..66a94145fef 100644--- a/zerver/tests/test_bots.py+++ b/zerver/tests/test_bots.py@@ -1179,6 +1179,139 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):result = self.client_patch("/json/bots/{}".format(self.example_user("hamlet").id), bot_info)self.assert_json_error(result, "No such bot")+ def test_patch_bot_short_name(self) -> None:+ self.login("hamlet")+ bot_info = {+ "full_name": "The Bot of Hamlet",+ "short_name": "hambot",+ }+ result = self.client_post("/json/bots", bot_info)+ self.assert_json_success(result)+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Bot owner can change short_name+ bot_info = {+ "short_name": "newbot",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ self.assert_json_success(result)++ bot.refresh_from_db()+ self.assertEqual(bot.email, "[email protected]")++ def test_patch_bot_short_name_admin(self) -> None:+ self.login("hamlet")+ bot_info = {+ "full_name": "The Bot of Hamlet",+ "short_name": "hambot",+ }+ result = self.client_post("/json/bots", bot_info)+ self.assert_json_success(result)+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Admin can change any bot's short_name+ self.login("iago")+ bot_info = {+ "short_name": "adminchanged",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ self.assert_json_success(result)++ bot.refresh_from_db()+ self.assertEqual(bot.email, "[email protected]")++ def test_patch_bot_short_name_unauthorized(self) -> None:+ self.login("hamlet")+ self.create_bot()+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Non-owner, non-admin cannot change+ self.login("cordelia")+ bot_info = {+ "short_name": "unauthorized",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ self.assert_json_error(result, "Insufficient permission")++ def test_patch_bot_short_name_duplicate(self) -> None:+ self.login("hamlet")+ # Create first bot+ bot_info = {+ "full_name": "Bot 1",+ "short_name": "bot1",+ }+ result = self.client_post("/json/bots", bot_info)+ self.assert_json_success(result)++ # Create second bot+ bot_info = {+ "full_name": "Bot 2",+ "short_name": "bot2",+ }+ result = self.client_post("/json/bots", bot_info)+ self.assert_json_success(result)+ bot2 = self.get_bot_user("[email protected]")++ # Try to change bot2's short_name to bot1's+ bot_info = {+ "short_name": "bot1",+ }+ result = self.client_patch(f"/json/bots/{bot2.id}", bot_info)+ self.assert_json_error(result, "Email address already in use")++ def test_patch_bot_short_name_invalid(self) -> None:+ self.login("hamlet")+ self.create_bot()+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Empty short_name should fail+ bot_info = {+ "short_name": "",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ self.assert_json_error(result, "Bad name or username")++ def test_patch_bot_short_name_no_change(self) -> None:+ self.login("hamlet")+ self.create_bot()+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Changing to the same short_name should be a no-op+ bot_info = {+ "short_name": "hambot",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ self.assert_json_success(result)++ bot.refresh_from_db()+ self.assertEqual(bot.email, "[email protected]")++ def test_patch_bot_short_name_invalid_fake_email_domain(self) -> None:+ self.login("hamlet")+ # Create bot first without the invalid domain setting+ self.create_bot()+ email = "[email protected]"+ bot = self.get_bot_user(email)++ # Now try to change short_name with invalid FAKE_EMAIL_DOMAIN+ with override_settings(+ FAKE_EMAIL_DOMAIN="invaliddomain", REALM_HOSTS={"zulip": "127.0.0.1"}+ ):+ bot_info = {+ "short_name": "newbot",+ }+ result = self.client_patch(f"/json/bots/{bot.id}", bot_info)+ error_message = (+ "Can't change bot email until FAKE_EMAIL_DOMAIN is correctly configured.\n"+ "Please contact your server administrator."+ )+ self.assert_json_error(result, error_message)+def test_patch_bot_owner(self) -> None:self.login("hamlet")othello = self.example_user("othello")diff --git a/zerver/views/users.py b/zerver/views/users.pyindex 5a3b282df81..e13226ce22b 100644--- a/zerver/views/users.py+++ b/zerver/views/users.py@@ -460,9 +460,35 @@ def patch_bot_backend(role: Json[RoleParamType] | None = None,service_interface: Json[int] = 1,service_payload_url: Json[Annotated[str, AfterValidator(check_url)]] | None = None,+ short_name: str | None = None,) -> HttpResponse:bot = access_bot_by_id(user_profile, bot_id)+ # Handle short_name change+ if short_name is not None:+ try:+ _validated_short_name, new_email = validate_short_name_and_construct_bot_email(+ short_name, user_profile.realm+ )+ except InvalidFakeEmailDomainError:+ raise JsonableError(+ _(+ "Can't change bot email until FAKE_EMAIL_DOMAIN is correctly configured.\n"+ "Please contact your server administrator."+ )+ )+ if new_email != bot.email:+ try:+ validate_email_not_already_in_realm(+ user_profile.realm,+ new_email,+ verbose=False,+ allow_inactive_mirror_dummies=False,+ )+ except ValidationError:+ raise JsonableError(_("Email address already in use"))+ do_change_user_delivery_email(bot, new_email, acting_user=user_profile)+if full_name is not None:check_change_bot_full_name(bot, full_name, user_profile)