Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
bots: Confirm before regenerating a bot's API key.
Dhruv Shetty5f9e0533a5f7
diff --git a/starlight_help/src/content/docs/manage-a-bot.mdx b/starlight_help/src/content/docs/manage-a-bot.mdxindex 60c5cf05b08..5698672720f 100644--- a/starlight_help/src/content/docs/manage-a-bot.mdx+++ b/starlight_help/src/content/docs/manage-a-bot.mdx@@ -6,6 +6,7 @@ import {TabItem, Tabs} from "@astrojs/starlight/components";import FlattenedSteps from "../../components/FlattenedSteps.astro";import NavigationSteps from "../../components/NavigationSteps.astro";+import ZulipNote from "../../components/ZulipNote.astro";import ZulipTip from "../../components/ZulipTip.astro";import AdminOnly from "../include/_AdminOnly.mdx";@@ -104,8 +105,13 @@ Only a bot's owner has access to its API key.<ZulipTip>To generate a new API key, click the **generate new API key** (<RefreshIcon />)- icon.+ icon, and then click **Generate new key** to confirm.</ZulipTip>++ <ZulipNote>+ Generating a new API key invalidates the bot's current key. Any+ integrations using the old key will stop working until you update them.+ </ZulipNote></FlattenedSteps>## Related articlesdiff --git a/web/src/bot_helper.ts b/web/src/bot_helper.tsindex bd839f256a8..0b3335d8754 100644--- a/web/src/bot_helper.ts+++ b/web/src/bot_helper.ts@@ -13,7 +13,7 @@ import * as channel from "./channel.ts";import * as clipboard_handler from "./clipboard_handler.ts";import {show_copied_confirmation} from "./copied_tooltip.ts";import * as dialog_widget from "./dialog_widget.ts";-import {$t_html} from "./i18n.ts";+import {$t, $t_html} from "./i18n.ts";import {realm} from "./state_data.ts";export function validate_bot_short_name(value: string): boolean {@@ -148,6 +148,8 @@ async function copy_zuliprc_content(bot: Bot, api_key: string): Promise<void> {});}+const REGENERATE_WARNING_ID = "bot-api-key-regenerate-warning";+export async function show_api_key_modal(bot_id: number): Promise<void> {const api_key = await fetch_bot_api_key(bot_id,@@ -181,37 +183,95 @@ export async function show_api_key_modal(bot_id: number): Promise<void> {});}+const REGENERATE_CONFIRMATION_BANNER: banners.Banner = {+ intent: "warning",+ label: $t({+ defaultMessage:+ "This invalidates the current API key. Integrations using the old key will stop working.",+ }),+ label_id: REGENERATE_WARNING_ID,+ buttons: [+ {+ variant: "subtle",+ label: $t({defaultMessage: "Generate new key"}),+ custom_classes: "bot-modal-confirm-regenerate-bot-api-key",+ "aria-describedby": REGENERATE_WARNING_ID,+ },+ ],+ close_button: false,+ custom_classes: "banner-in-modal",+};++// Focus Cancel rather than Confirm, so that pressing Enter twice backs+// out instead of generating a new key.+function show_api_key_regenerate_confirmation($container: JQuery): void {+ $container.find(".bot-modal-api-key-error").hide();+ $container.find(".bot-modal-regenerate-bot-api-key").addClass("hide");+ banners.open(REGENERATE_CONFIRMATION_BANNER, $container.find(".bot-api-key-regenerate-banner"));+ $container+ .find(".bot-modal-cancel-regenerate-bot-api-key")+ .removeClass("hide")+ .trigger("focus");+}++function hide_api_key_regenerate_confirmation($container: JQuery): void {+ banners.close($container.find(".bot-api-key-regenerate-banner .banner"));+ $container+ .find(".bot-modal-cancel-regenerate-bot-api-key")+ .prop("disabled", false)+ .addClass("hide");+ $container.find(".bot-modal-regenerate-bot-api-key").removeClass("hide").trigger("focus");+}++function show_api_key_regenerate_error($container: JQuery, message_html: string): void {+ $container.find(".bot-modal-api-key-error").html(message_html).show();+}+export function initialize_bot_click_handlers(): void {$("body").on("click", "button.bot-modal-regenerate-bot-api-key", (e) => {e.preventDefault();- const bot_id = Number.parseInt(- $(e.currentTarget).closest("span").attr("data-user-id")!,- 10,- );- const $row = $(e.currentTarget).closest(".input-group");-- void channel.post({- url: `/json/bots/${encodeURIComponent(bot_id)}/api_key/regenerate`,- success(data) {- const parsed_data = z- .object({- api_key: z.string(),- })- .parse(data);-- $row.find(".api-key").val(parsed_data.api_key);- $row.closest(".bot-api-key-container").attr("data-api-key", parsed_data.api_key);- $row.find(".bot-modal-api-key-error").hide();- },- error(xhr) {- const parsed = z.object({msg: z.string()}).safeParse(xhr.responseJSON);- if (parsed.success && parsed.data.msg) {- $row.find(".bot-modal-api-key-error").text(parsed.data.msg).show();- }- },- });+ show_api_key_regenerate_confirmation($(e.currentTarget).closest(".bot-api-key-container"));+ });++ $("body").on("click", "button.bot-modal-cancel-regenerate-bot-api-key", (e) => {+ e.preventDefault();+ hide_api_key_regenerate_confirmation($(e.currentTarget).closest(".bot-api-key-container"));});+ $("body").on(+ "click",+ "button.bot-modal-confirm-regenerate-bot-api-key",+ function (this: HTMLElement, e) {+ e.preventDefault();+ const $button = $(this);+ const $container = $button.closest(".bot-api-key-container");+ const bot_id = Number.parseInt($container.attr("data-user-id")!, 10);++ $container.find(".bot-modal-cancel-regenerate-bot-api-key").prop("disabled", true);+ $button.prop("disabled", true);+ buttons.show_button_loading_indicator($button);+ const failure_message_html = $t_html({+ defaultMessage: "Failed to generate new API key",+ });+ void channel.post({+ url: `/json/bots/${encodeURIComponent(bot_id)}/api_key/regenerate`,+ success(data) {+ hide_api_key_regenerate_confirmation($container);+ const parsed_data = z.object({api_key: z.string()}).parse(data);+ $container.find(".api-key").val(parsed_data.api_key);+ $container.attr("data-api-key", parsed_data.api_key);+ },+ error(xhr) {+ hide_api_key_regenerate_confirmation($container);+ show_api_key_regenerate_error(+ $container,+ channel.xhr_error_message(failure_message_html, xhr),+ );+ },+ });+ },+ );+$("body").on("click", "button.download-bot-zuliprc", function () {void (async () => {const $bot_info = $(this).closest("#bot-edit-form");diff --git a/web/styles/banners.css b/web/styles/banners.cssindex 466c0ec89a6..79764b51c65 100644--- a/web/styles/banners.css+++ b/web/styles/banners.css@@ -151,6 +151,29 @@}}+.banner-in-modal {+ .banner-content {+ flex-direction: column;+ }++ .banner-label {+ /* Reset to initial value */+ flex: 0 1 auto;+ }++ .banner-action-buttons {+ max-width: 100%;+ }++ .action-button {+ min-width: 0;+ }++ .action-button-label {+ max-width: none;+ }+}+.banner-neutral {background-color: var(--color-background-neutral-banner);color: var(--color-text-neutral-banner);diff --git a/web/styles/settings.css b/web/styles/settings.cssindex 2932d88318c..2cd50a44b4f 100644--- a/web/styles/settings.css+++ b/web/styles/settings.css@@ -480,6 +480,11 @@ select.settings_select {.modal_text_input {margin-bottom: 0;}++ .bot-api-key-regenerate-banner:has(.banner) {+ /* Only space the banner off the API key row when it's present. */+ margin-top: 0.625em; /* 10px at 16px/1em */+ }}#zuliprc-section {diff --git a/web/templates/settings/bot_api_key_details.hbs b/web/templates/settings/bot_api_key_details.hbsindex 51230896959..c7d3fb1fcc8 100644--- a/web/templates/settings/bot_api_key_details.hbs+++ b/web/templates/settings/bot_api_key_details.hbs@@ -4,7 +4,7 @@<div class="api-key-details-container"><input type="text" autocomplete="off" name="api-key" class="modal_text_input api-key inline-block" value="{{ api_key }}" readonly/><div class="buttons-container">- <span data-user-id="{{bot_id}}">+ <span>{{> ../components/icon_buttonicon="refresh-cw"intent="brand"@@ -12,6 +12,16 @@data-tippy-content=(t "Generate new API key")}}</span>+ <span>+ {{> ../components/icon_button+ icon="close"+ intent="neutral"+ hidden=true+ custom_classes="bot-modal-cancel-regenerate-bot-api-key tippy-zulip-delayed-tooltip"+ aria-label=(t "Cancel new key generation")+ data-tippy-content=(t "Cancel new key generation")+ }}+ </span><span>{{> ../components/icon_buttonicon="copy"@@ -23,6 +33,7 @@</span></div></div>+ <div class="bot-api-key-regenerate-banner banner-wrapper"></div><div class="bot-modal-api-key-error text-error"></div></div></div>diff --git a/web/tests/settings_bots.test.cjs b/web/tests/settings_bots.test.cjsindex e341705c96a..4f45535b2c2 100644--- a/web/tests/settings_bots.test.cjs+++ b/web/tests/settings_bots.test.cjs@@ -4,8 +4,13 @@ const assert = require("node:assert/strict");const {make_realm} = require("./lib/example_realm.cjs");const {make_user} = require("./lib/example_user.cjs");-const {zrequire} = require("./lib/namespace.cjs");-const {run_test} = require("./lib/test.cjs");+const {mock_esm, zrequire} = require("./lib/namespace.cjs");+const {run_test, noop} = require("./lib/test.cjs");+const {$} = require("./lib/zjquery.cjs");++const banners = mock_esm("../src/banners");+const buttons = mock_esm("../src/buttons");+const channel = mock_esm("../src/channel");const bot_data = zrequire("bot_data");const bot_helper = zrequire("bot_helper");@@ -81,6 +86,104 @@ test("generate_zuliprc_content", () => {assert.equal(content, expected);});+test("regenerate_bot_api_key_confirmation_banner", ({override}) => {+ bot_helper.initialize_bot_click_handlers();++ const $container = $.create("bot-api-key-container-stub");+ $container.attr("data-user-id", "1");++ const $regenerate_button = $(".regenerate-button-stub");+ const $cancel_button = $(".cancel-stub");+ const $confirm_button = $(".confirm-stub");+ $regenerate_button.set_closest_results(".bot-api-key-container", $container);+ $cancel_button.set_closest_results(".bot-api-key-container", $container);+ $confirm_button.set_closest_results(".bot-api-key-container", $container);++ const $api_key_input = $.create("api-key-input-stub");+ const $error = $.create("api-key-error-stub");+ const $banner = $.create("regenerate-banner-stub");+ $container.set_find_results(".bot-modal-regenerate-bot-api-key", $regenerate_button);+ $container.set_find_results(".bot-modal-cancel-regenerate-bot-api-key", $cancel_button);+ $container.set_find_results(".api-key", $api_key_input);+ $container.set_find_results(".bot-modal-api-key-error", $error);+ $container.set_find_results(+ ".bot-api-key-regenerate-banner",+ $.create("regenerate-banner-container-stub"),+ );+ $container.set_find_results(".bot-api-key-regenerate-banner .banner", $banner);++ let opened_banner;+ override(banners, "open", (banner) => {+ opened_banner = banner;+ return $banner;+ });+ let $closed_banner;+ override(banners, "close", ($banner_to_close) => {+ $closed_banner = $banner_to_close;+ });+ override(buttons, "show_button_loading_indicator", noop);++ let post_opts;+ override(channel, "post", (opts) => {+ post_opts = opts;+ });+ override(+ channel,+ "xhr_error_message",+ (message_html, xhr) => `${message_html} (status ${xhr.status})`,+ );++ const regenerate_handler = $("body").get_on_handler(+ "click",+ "button.bot-modal-regenerate-bot-api-key",+ );++ regenerate_handler({preventDefault: noop, currentTarget: ".regenerate-button-stub"});+ assert.equal(post_opts, undefined);+ assert.equal(opened_banner.intent, "warning");+ assert.ok($cancel_button.is_focused());++ const [confirm_button] = opened_banner.buttons;+ // Confirm describes itself with the banner's own warning text, so the+ // consequences are announced when focus reaches it.+ assert.equal(confirm_button["aria-describedby"], opened_banner.label_id);+ const cancel_handler = $("body").get_on_handler(+ "click",+ "button.bot-modal-cancel-regenerate-bot-api-key",+ );+ const confirm_handler = $("body").get_on_handler(+ "click",+ `button.${confirm_button.custom_classes}`,+ );++ cancel_handler({preventDefault: noop, currentTarget: ".cancel-stub"});+ assert.equal(post_opts, undefined);+ assert.equal($closed_banner[0], $banner[0]);+ assert.ok($regenerate_button.is_focused());++ regenerate_handler({preventDefault: noop, currentTarget: ".regenerate-button-stub"});+ confirm_handler.call(".confirm-stub", {preventDefault: noop});+ assert.equal(post_opts.url, "/json/bots/1/api_key/regenerate");++ post_opts.success({api_key: "new-api-key"});+ assert.equal($api_key_input.val(), "new-api-key");+ assert.equal($container.attr("data-api-key"), "new-api-key");+ assert.equal($closed_banner[0], $banner[0]);++ // A failed key generation backs out of the confirmation and reports why+ // below the key.+ regenerate_handler({preventDefault: noop, currentTarget: ".regenerate-button-stub"});+ confirm_handler.call(".confirm-stub", {preventDefault: noop});+ post_opts.error({status: 400, responseJSON: {msg: "Insufficient permission"}});+ assert.equal($error.html(), "translated: Failed to generate new API key (status 400)");+ assert.ok($error.visible());+ assert.equal($closed_banner[0], $banner[0]);++ // Asking for a new key again clears the stale error from the failed attempt.+ regenerate_handler({preventDefault: noop, currentTarget: ".regenerate-button-stub"});+ assert.ok(!$error.visible());+});+test("generate_botserverrc_content", () => {const user = {email: "[email protected]",