mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 14:33:38 +00:00
🧹 fix: Remove Disconnected Slack Workspaces (#17834)
* fix: Allow Admins to Remove Disconnected Slack Workspaces * fix: Use Workspace Status Chips and One Confirmation Action * fix: Confirm Workspace Removal in a Stacked Dialog * fix: Align Confirmation Cancel Action to the Left
This commit is contained in:
parent
fdf75e0174
commit
567aeefe93
12 changed files with 298 additions and 60 deletions
|
|
@ -32,4 +32,5 @@ router.post(
|
|||
handlers.connect,
|
||||
);
|
||||
router.delete('/workspaces/:workspaceId', requireJwtAuth, requireSameOrigin, handlers.disconnect);
|
||||
router.post('/workspaces/:workspaceId/remove', requireJwtAuth, requireSameOrigin, handlers.remove);
|
||||
module.exports = router;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ jest.mock('librechat-data-provider', () => {
|
|||
getSlackApps: jest.fn(),
|
||||
connectSlackWorkspace: jest.fn(),
|
||||
disconnectSlackWorkspace: jest.fn(),
|
||||
removeSlackWorkspace: jest.fn(),
|
||||
cancelSlackWorkspaceInstall: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
|
@ -77,6 +78,9 @@ beforeEach(() => {
|
|||
expiresInSeconds: 600,
|
||||
});
|
||||
cancel = jest.spyOn(dataService, 'cancelSlackWorkspaceInstall').mockResolvedValue(undefined);
|
||||
jest.spyOn(dataService, 'removeSlackWorkspace').mockImplementation(async () => {
|
||||
response = { ...response, workspaces: [] };
|
||||
});
|
||||
popup.closed = false;
|
||||
popup.location.href = '';
|
||||
popup.close.mockClear();
|
||||
|
|
@ -127,10 +131,13 @@ test('disconnect requires confirmation and refreshes the org workspace state', a
|
|||
const user = userEvent.setup();
|
||||
page();
|
||||
await screen.findByText('Engineering');
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'com_ui_slack_workspaces_remove' }),
|
||||
).not.toBeInTheDocument();
|
||||
const appReads = jest.mocked(dataService.getSlackApps).mock.calls.length;
|
||||
await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' }));
|
||||
expect(disconnect).not.toHaveBeenCalled();
|
||||
const confirmation = screen.getByRole('group', { name: 'com_ui_slack_workspaces_confirm' });
|
||||
const confirmation = screen.getByRole('dialog', { name: 'com_ui_slack_workspaces_disconnect' });
|
||||
await user.click(
|
||||
within(confirmation).getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' }),
|
||||
);
|
||||
|
|
@ -142,7 +149,47 @@ test('disconnect requires confirmation and refreshes the org workspace state', a
|
|||
expect(
|
||||
screen.queryByRole('button', { name: 'com_ui_slack_workspaces_reconnect' }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('group')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('only admins can confirm removal of a disconnected workspace', async () => {
|
||||
const user = userEvent.setup();
|
||||
response.workspaces = [{ ...workspace, status: 'disconnected' }];
|
||||
const { client } = page();
|
||||
await user.click(await screen.findByRole('button', { name: 'com_ui_slack_workspaces_remove' }));
|
||||
expect(dataService.removeSlackWorkspace).not.toHaveBeenCalled();
|
||||
expect(
|
||||
screen.getByRole('dialog', { name: 'com_ui_slack_workspaces_remove' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button', { name: 'com_ui_slack_workspaces_remove' })).toHaveLength(1);
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
expect(screen.getByRole('button', { name: 'com_ui_slack_workspaces_remove' })).toHaveFocus();
|
||||
await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_remove' }));
|
||||
await user.click(
|
||||
within(screen.getByRole('dialog')).getByRole('button', {
|
||||
name: 'com_ui_slack_workspaces_remove',
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(dataService.removeSlackWorkspace).toHaveBeenCalledWith('workspace-1', 'revision-1'),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByText('Engineering')).not.toBeInTheDocument());
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('heading', { name: 'com_ui_slack_workspaces_title' })).toHaveFocus(),
|
||||
);
|
||||
response = {
|
||||
...response,
|
||||
canManage: false,
|
||||
workspaces: [{ ...workspace, status: 'disconnected' }],
|
||||
};
|
||||
await act(async () => {
|
||||
await client.invalidateQueries([QueryKeys.slackWorkspaces]);
|
||||
});
|
||||
await screen.findByText('Engineering');
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'com_ui_slack_workspaces_remove' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('keeps the confirmed revision when workspace metadata changes before disconnect', async () => {
|
||||
|
|
@ -157,15 +204,15 @@ test('keeps the confirmed revision when workspace metadata changes before discon
|
|||
});
|
||||
disconnect.mockRejectedValueOnce(new Error('Workspace changed'));
|
||||
await user.click(
|
||||
within(screen.getByRole('group')).getByRole('button', {
|
||||
within(screen.getByRole('dialog')).getByRole('button', {
|
||||
name: 'com_ui_slack_workspaces_disconnect',
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(disconnect).toHaveBeenLastCalledWith('workspace-1', 'revision-1'));
|
||||
await waitFor(() => expect(screen.queryByRole('group')).not.toBeInTheDocument());
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
await user.click(screen.getByRole('button', { name: 'com_ui_slack_workspaces_disconnect' }));
|
||||
await user.click(
|
||||
within(screen.getByRole('group')).getByRole('button', {
|
||||
within(screen.getByRole('dialog')).getByRole('button', {
|
||||
name: 'com_ui_slack_workspaces_disconnect',
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useCallback, useEffect, useId, useRef, useState } from 'react';
|
||||
import { Button, Spinner } from '@librechat/client';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { MutationKeys, QueryKeys, dataService } from 'librechat-data-provider';
|
||||
import { Button, Chip, OGDialog, OGDialogTemplate, Spinner } from '@librechat/client';
|
||||
import type { SlackWorkspace } from 'librechat-data-provider';
|
||||
import { watchOAuthSettlements } from '~/data-provider/PullRequest/signIn';
|
||||
import { useSlackWorkspaces } from './useSlackWorkspaces';
|
||||
|
|
@ -30,6 +30,9 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
const [pending, setPending] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [confirm, setConfirm] = useState<SlackWorkspace | null>(null);
|
||||
const actionRef = useRef<HTMLButtonElement | null>(null);
|
||||
const headingRef = useRef<HTMLHeadingElement | null>(null);
|
||||
const settingsRef = useRef<HTMLElement | null>(null);
|
||||
const flow = useRef<string | null>(null);
|
||||
const deadline = useRef<ReturnType<typeof setTimeout>>();
|
||||
const mounted = useRef(true);
|
||||
|
|
@ -48,13 +51,18 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
mutationFn: (input: { workspaceId?: string; appId?: string }) =>
|
||||
dataService.connectSlackWorkspace(input.workspaceId, input.appId),
|
||||
});
|
||||
const disconnect = useMutation({
|
||||
mutationKey: [MutationKeys.slackWorkspaces, principalKey, 'disconnect'],
|
||||
const retire = useMutation({
|
||||
mutationKey: [MutationKeys.slackWorkspaces, principalKey, 'retire'],
|
||||
mutationFn: (workspace: SlackWorkspace) =>
|
||||
dataService.disconnectSlackWorkspace(workspace.workspaceId, workspace.revision),
|
||||
workspace.status === 'disconnected'
|
||||
? dataService.removeSlackWorkspace(workspace.workspaceId, workspace.revision)
|
||||
: dataService.disconnectSlackWorkspace(workspace.workspaceId, workspace.revision),
|
||||
onSettled: async () => {
|
||||
setConfirm(null);
|
||||
await refresh();
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
setConfirm(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
const cancel = useMutation({
|
||||
|
|
@ -142,21 +150,30 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
|
||||
const first = status.data?.pages[0];
|
||||
const workspaces = status.data?.pages.flatMap((page) => page.workspaces) ?? [];
|
||||
const activeTone = first?.configured ? 'success' : 'warning';
|
||||
if (first && !first.configured && workspaces.length === 0) return null;
|
||||
const busy = pending || connect.isLoading || disconnect.isLoading || cancel.isLoading;
|
||||
const confirmLabel =
|
||||
confirm?.status === 'disconnected'
|
||||
? 'com_ui_slack_workspaces_remove_confirm'
|
||||
: 'com_ui_slack_workspaces_confirm';
|
||||
const confirmAction =
|
||||
confirm?.status === 'disconnected'
|
||||
? 'com_ui_slack_workspaces_remove'
|
||||
: 'com_ui_slack_workspaces_disconnect';
|
||||
const busy = pending || connect.isLoading || retire.isLoading || cancel.isLoading;
|
||||
return (
|
||||
<section className="space-y-4" aria-labelledby={`${id}-title`}>
|
||||
<h2 id={`${id}-title`} className="font-medium">
|
||||
<h2 ref={headingRef} tabIndex={-1} id={`${id}-title`} className="font-medium">
|
||||
{localize('com_ui_slack_workspaces_title')}
|
||||
</h2>
|
||||
<p className="text-text-secondary">{localize('com_ui_slack_workspaces_description')}</p>
|
||||
{status.isLoading && <Spinner />}
|
||||
{(status.isError || failed || disconnect.isError || cancel.isError) && (
|
||||
{(status.isError || failed || retire.isError || cancel.isError) && (
|
||||
<div role="alert" className="space-y-2">
|
||||
<p>
|
||||
{localize(
|
||||
channelErrorLabel(
|
||||
connect.error ?? disconnect.error ?? cancel.error ?? status.error,
|
||||
connect.error ?? retire.error ?? cancel.error ?? status.error,
|
||||
'com_ui_slack_workspaces_error',
|
||||
),
|
||||
)}
|
||||
|
|
@ -166,7 +183,7 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
onClick={() => {
|
||||
setFailed(false);
|
||||
connect.reset();
|
||||
disconnect.reset();
|
||||
retire.reset();
|
||||
cancel.reset();
|
||||
void status.refetch();
|
||||
}}
|
||||
|
|
@ -203,8 +220,15 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
key={workspace.workspaceId}
|
||||
className="border-border-light space-y-2 rounded-lg border p-3"
|
||||
>
|
||||
<p className="font-medium break-words">{workspace.teamName}</p>
|
||||
<p>{localize(workspaceStatusLabel(workspace, first?.configured))}</p>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<p className="min-w-0 font-medium break-words">{workspace.teamName}</p>
|
||||
<Chip
|
||||
tone={workspace.status === 'disconnected' ? 'neutral' : activeTone}
|
||||
className="shrink-0"
|
||||
>
|
||||
{localize(workspaceStatusLabel(workspace, first?.configured))}
|
||||
</Chip>
|
||||
</div>
|
||||
{first?.canManage && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{first.configured && workspace.status === 'active' && (
|
||||
|
|
@ -216,32 +240,21 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
{localize('com_ui_slack_workspaces_reconnect')}
|
||||
</Button>
|
||||
)}
|
||||
{workspace.status === 'active' && (
|
||||
<Button variant="outline" disabled={busy} onClick={() => setConfirm(workspace)}>
|
||||
{localize('com_ui_slack_workspaces_disconnect')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{confirm?.workspaceId === workspace.workspaceId && (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={localize('com_ui_slack_workspaces_confirm')}
|
||||
className="space-y-2"
|
||||
>
|
||||
<p>{localize('com_ui_slack_workspaces_confirm')}</p>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={busy}
|
||||
onClick={() => disconnect.mutate(confirm)}
|
||||
>
|
||||
{localize('com_ui_slack_workspaces_disconnect')}
|
||||
</Button>
|
||||
<Button variant="outline" disabled={busy} onClick={() => setConfirm(null)}>
|
||||
{localize('com_ui_cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={(event) => {
|
||||
actionRef.current = event.currentTarget;
|
||||
settingsRef.current = event.currentTarget.closest<HTMLElement>('[role="dialog"]');
|
||||
setConfirm(workspace);
|
||||
}}
|
||||
>
|
||||
{localize(
|
||||
workspace.status === 'disconnected'
|
||||
? 'com_ui_slack_workspaces_remove'
|
||||
: 'com_ui_slack_workspaces_disconnect',
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -255,6 +268,41 @@ function OwnedWorkspaces({ principalKey }: { principalKey: string }) {
|
|||
{localize('com_ui_slack_workspaces_more')}
|
||||
</Button>
|
||||
)}
|
||||
<OGDialog
|
||||
open={confirm !== null && first?.canManage === true}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !retire.isLoading) setConfirm(null);
|
||||
}}
|
||||
>
|
||||
<OGDialogTemplate
|
||||
className="max-w-md"
|
||||
footerClassName="sm:justify-between"
|
||||
title={localize(confirmAction)}
|
||||
description={confirm?.teamName}
|
||||
main={<p className="text-text-secondary text-sm">{localize(confirmLabel)}</p>}
|
||||
cancelDisabled={retire.isLoading}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (actionRef.current?.isConnected) actionRef.current.focus();
|
||||
else if (headingRef.current?.isConnected) headingRef.current.focus();
|
||||
else settingsRef.current?.focus();
|
||||
}}
|
||||
selection={
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={busy || !confirm || first?.canManage !== true}
|
||||
aria-busy={retire.isLoading}
|
||||
onClick={() => {
|
||||
if (confirm) retire.mutate(confirm);
|
||||
}}
|
||||
>
|
||||
{retire.isLoading && <Spinner className="size-4" aria-hidden="true" />}
|
||||
{localize(confirmAction)}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</OGDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@
|
|||
"com_ui_slack_workspaces_empty": "No Slack workspaces are connected.",
|
||||
"com_ui_slack_workspaces_admin": "An organization administrator with agent management permission can connect and disconnect workspaces.",
|
||||
"com_ui_slack_workspaces_waiting": "Finish connecting in the Slack window. Your workspace list will update when you return.",
|
||||
"com_ui_slack_workspaces_remove": "Remove workspace",
|
||||
"com_ui_slack_workspaces_remove_confirm": "Remove this disconnected workspace from your organization’s list? Connecting again requires a fresh installation. This does not uninstall the app from Slack.",
|
||||
"com_ui_slack_workspaces_confirm": "Disconnect this workspace for your organization? New Slack requests will stop. The Slack app will remain installed, and completed actions cannot be undone.",
|
||||
"com_ui_slack_workspaces_more": "Show more workspaces",
|
||||
"com_ui_slack_workspaces_error": "Could not update Slack workspaces. Check the workspace list and try again. Allow pop-ups when connecting a workspace.",
|
||||
|
|
@ -3962,7 +3964,7 @@
|
|||
"com_ui_slack_apps_signing_secret": "Signing secret",
|
||||
"com_ui_slack_apps_update": "Replace credentials",
|
||||
"com_ui_slack_apps_remove": "Remove app",
|
||||
"com_ui_slack_apps_confirm_remove": "Remove this app’s saved credentials? Disconnect its workspaces first. This does not delete the app from Slack.",
|
||||
"com_ui_slack_apps_confirm_remove": "Remove this app’s saved credentials and disconnected workspaces from the list? Disconnect its active workspaces first. This does not delete the app from Slack.",
|
||||
"com_ui_slack_apps_error": "Could not save or remove the Slack app. Refresh and try again. Disconnect active workspaces before removing an app.",
|
||||
"com_ui_slack_apps_saved": "Slack app saved. Finish its settings in Slack, then install a workspace.",
|
||||
"com_ui_slack_apps_callbacks": "Configure these URLs in your Slack app",
|
||||
|
|
|
|||
|
|
@ -60,6 +60,13 @@ for (const theme of ['light', 'dark']) {
|
|||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname.endsWith('/workspace-browser/remove')) {
|
||||
expect(route.request().method()).toBe('POST');
|
||||
expect(route.request().postDataJSON()).toEqual({ revision: 'installed' });
|
||||
workspaces = [];
|
||||
await route.fulfill({ status: 204 });
|
||||
return;
|
||||
}
|
||||
if (url.pathname.endsWith('/connect')) {
|
||||
expect(route.request().postDataJSON()).toMatchObject({ appId: 'A123' });
|
||||
attempt++;
|
||||
|
|
@ -147,8 +154,8 @@ for (const theme of ['light', 'dark']) {
|
|||
.getByRole('button', { name: 'Disconnect workspace', exact: true })
|
||||
.click();
|
||||
expect(disconnected).toBe(0);
|
||||
await workspacesPanel
|
||||
.getByRole('group')
|
||||
await page
|
||||
.getByRole('dialog', { name: 'Disconnect workspace', exact: true })
|
||||
.getByRole('button', {
|
||||
name: 'Disconnect workspace',
|
||||
exact: true,
|
||||
|
|
@ -156,6 +163,32 @@ for (const theme of ['light', 'dark']) {
|
|||
.click();
|
||||
await expect(workspacesPanel.getByText('Disconnected', { exact: true })).toBeVisible();
|
||||
expect(disconnected).toBe(1);
|
||||
await workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }).click();
|
||||
const removal = page.getByRole('dialog', { name: 'Remove workspace', exact: true });
|
||||
await expect(removal.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(removal).not.toBeVisible();
|
||||
await expect(
|
||||
workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }),
|
||||
).toBeFocused();
|
||||
await workspacesPanel.getByRole('button', { name: 'Remove workspace', exact: true }).click();
|
||||
await expect(removal).toContainText('This does not uninstall the app from Slack.');
|
||||
await expect(
|
||||
removal.getByRole('button', { name: 'Remove workspace', exact: true }),
|
||||
).toHaveCount(1);
|
||||
if (process.env.E2E_SLACK_WORKSPACES_VISUAL_PREFIX) {
|
||||
await removal.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({
|
||||
animations: 'disabled',
|
||||
path: `${process.env.E2E_SLACK_WORKSPACES_VISUAL_PREFIX}-remove-${theme}.png`,
|
||||
});
|
||||
}
|
||||
await removal.getByRole('button', { name: 'Remove workspace', exact: true }).click();
|
||||
await expect(workspacesPanel.getByText('Example engineering')).toHaveCount(0);
|
||||
await expect(workspacesPanel.getByText('No Slack workspaces are connected.')).toBeVisible();
|
||||
await expect(
|
||||
workspacesPanel.getByRole('heading', { name: 'Organization Slack workspaces', exact: true }),
|
||||
).toBeFocused();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('#prompt-textarea')).toBeVisible();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ export interface SlackWorkspaceHandlers {
|
|||
get: RequestHandler;
|
||||
connect: RequestHandler;
|
||||
disconnect: RequestHandler;
|
||||
remove: RequestHandler;
|
||||
cancel: RequestHandler;
|
||||
callback: RequestHandler;
|
||||
}
|
||||
|
|
@ -89,6 +90,19 @@ export function createSlackWorkspaceHandlers(deps: {
|
|||
}
|
||||
};
|
||||
|
||||
const workspaceAction = (action: 'disconnect' | 'remove') =>
|
||||
browser(async (req, res, principal) => {
|
||||
const id = identifier.safeParse(req.params.workspaceId);
|
||||
const body = z.object({ revision: identifier }).strict().safeParse(req.body);
|
||||
if (!id.success || !body.success) {
|
||||
res.status(400).json({ ok: false, error: { code: 'workspace_changed' } });
|
||||
return;
|
||||
}
|
||||
const result = await deps.service[action](principal, id.data, body.data.revision);
|
||||
if (!result.ok) res.status(result.error.code === 'forbidden' ? 403 : 409).json(result);
|
||||
else res.sendStatus(204);
|
||||
});
|
||||
|
||||
return {
|
||||
apps: browser(async (req, res, principal) => {
|
||||
const page = pageQuery.safeParse(req.query);
|
||||
|
|
@ -187,17 +201,8 @@ export function createSlackWorkspaceHandlers(deps: {
|
|||
);
|
||||
res.json(result.value);
|
||||
}),
|
||||
disconnect: browser(async (req, res, principal) => {
|
||||
const id = identifier.safeParse(req.params.workspaceId);
|
||||
const body = z.object({ revision: identifier }).strict().safeParse(req.body);
|
||||
if (!id.success || !body.success) {
|
||||
res.status(400).json({ ok: false, error: { code: 'workspace_changed' } });
|
||||
return;
|
||||
}
|
||||
const result = await deps.service.disconnect(principal, id.data, body.data.revision);
|
||||
if (!result.ok) res.status(result.error.code === 'forbidden' ? 403 : 409).json(result);
|
||||
else res.sendStatus(204);
|
||||
}),
|
||||
disconnect: workspaceAction('disconnect'),
|
||||
remove: workspaceAction('remove'),
|
||||
cancel: browser(async (req, res, principal) => {
|
||||
if (!/^[a-f0-9]{64}$/.test(req.params.flowId)) {
|
||||
res.status(400).json({ ok: false, error: { code: 'invalid_install' } });
|
||||
|
|
|
|||
|
|
@ -292,6 +292,7 @@ describe('Slack workspace installation', () => {
|
|||
server.post('/workspaces/apps/:appId/remove', handlers.removeApp);
|
||||
server.get('/workspaces/:workspaceId', handlers.get);
|
||||
server.delete('/workspaces/:workspaceId', handlers.disconnect);
|
||||
server.post('/workspaces/:workspaceId/remove', handlers.remove);
|
||||
server.post('/workspaces/connect', setOAuthSession, handlers.connect);
|
||||
server.delete('/workspaces/attempts/:flowId', handlers.cancel);
|
||||
server.get('/api/channels/workspaces/oauth/callback', handlers.callback);
|
||||
|
|
@ -376,6 +377,31 @@ describe('Slack workspace installation', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('requires current tenant-admin authority and a disconnected revision to remove a workspace', async () => {
|
||||
const { flow } = await start();
|
||||
const installed = await scoped(() => service.finish(flow, 'code'));
|
||||
if (!installed.ok) throw new Error(installed.error.code);
|
||||
const { workspaceId, revision } = installed.value;
|
||||
const remove = (body: object, tenant = 'org-a') =>
|
||||
http()
|
||||
.post(`/workspaces/${workspaceId}/remove`)
|
||||
.set('x-test-user', 'yes')
|
||||
.set('x-test-tenant', tenant)
|
||||
.set('x-test-user-tenant', tenant)
|
||||
.send(body);
|
||||
await remove({}).expect(400);
|
||||
await remove({ revision }).expect(409);
|
||||
await scoped(() => storage.disconnect(workspaceId, revision));
|
||||
const retired = await scoped(() => storage.read(workspaceId));
|
||||
await remove({ revision: retired!.revision }, 'org-b').expect(409);
|
||||
canManage.mockResolvedValue(false);
|
||||
await remove({ revision: retired!.revision }).expect(403);
|
||||
canManage.mockResolvedValue(true);
|
||||
await remove({ revision }).expect(409);
|
||||
await remove({ revision: retired!.revision }).expect(204);
|
||||
expect((await scoped(() => storage.list())).workspaces).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns one saved workspace as credential-free tenant metadata', async () => {
|
||||
const { flow } = await start();
|
||||
const installed = await scoped(() => service.finish(flow, 'test-code'));
|
||||
|
|
|
|||
|
|
@ -305,6 +305,16 @@ export function createSlackWorkspaceService(deps: {
|
|||
return installed.ok ? { ok: true, value: installed.workspace } : failure(installed.code);
|
||||
},
|
||||
|
||||
async remove(
|
||||
principal: SlackWorkspacePrincipal,
|
||||
workspaceId: string,
|
||||
expectedRevision: string,
|
||||
): Promise<Result<boolean>> {
|
||||
if (!inScope(principal) || !(await deps.canManage(principal))) return failure('forbidden');
|
||||
return (await deps.storage.remove(workspaceId, expectedRevision))
|
||||
? { ok: true, value: true }
|
||||
: failure('workspace_changed');
|
||||
},
|
||||
async disconnect(
|
||||
principal: SlackWorkspacePrincipal,
|
||||
workspaceId: string,
|
||||
|
|
|
|||
|
|
@ -230,6 +230,10 @@ export function disconnectSlackWorkspace(workspaceId: string, revision: string):
|
|||
return request.deleteWithOptions(endpoints.slackWorkspaces(workspaceId), { data: { revision } });
|
||||
}
|
||||
|
||||
export function removeSlackWorkspace(workspaceId: string, revision: string): Promise<void> {
|
||||
return request.post(`${endpoints.slackWorkspaces(workspaceId)}/remove`, { revision });
|
||||
}
|
||||
|
||||
export function cancelSlackWorkspaceInstall(flowId: string): Promise<void> {
|
||||
return request.delete(`${endpoints.slackWorkspaces()}/attempts/${encodeURIComponent(flowId)}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -148,9 +148,44 @@ describe('organization-owned Slack workspaces', () => {
|
|||
expect(await store.removeApp('A123', disconnected!.revision)).toBe('removed');
|
||||
expect(await store.app('A123')).toBeNull();
|
||||
expect((await store.apps()).apps).toEqual([]);
|
||||
expect((await store.list()).workspaces).toEqual([]);
|
||||
expect(await store.read(installed.workspace.workspaceId)).toMatchObject({
|
||||
status: 'disconnected',
|
||||
removedAt: expect.any(Date),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('removes only a current disconnected workspace and preserves installation fences', async () => {
|
||||
await scoped('org-a', () => start('original'));
|
||||
const installed = await scoped('org-a', () => finish('original'));
|
||||
if (!installed.ok) throw new Error('Test install failed');
|
||||
const { workspaceId, revision } = installed.workspace;
|
||||
expect(await scoped('org-a', () => store.remove(workspaceId, revision))).toBe(false);
|
||||
await scoped('org-a', () => start('delayed-before-disconnect'));
|
||||
await scoped('org-a', () => store.disconnect(workspaceId, revision));
|
||||
const retired = await scoped('org-a', () => store.read(workspaceId));
|
||||
expect(retired?.encryptedBotToken).toBeUndefined();
|
||||
expect(await scoped('org-b', () => store.remove(workspaceId, retired!.revision))).toBe(false);
|
||||
expect(await scoped('org-a', () => store.remove(workspaceId, revision))).toBe(false);
|
||||
expect(await scoped('org-a', () => store.remove(workspaceId, retired!.revision))).toBe(true);
|
||||
expect((await scoped('org-a', () => store.list())).workspaces).toEqual([]);
|
||||
expect(await scoped('org-a', () => store.read(workspaceId))).toMatchObject({
|
||||
status: 'disconnected',
|
||||
removedAt: expect.any(Date),
|
||||
});
|
||||
expect(await scoped('org-a', () => finish('delayed-before-disconnect'))).toEqual({
|
||||
ok: false,
|
||||
code: 'stale_install',
|
||||
});
|
||||
await scoped('org-a', () => start('fresh-install'));
|
||||
const fresh = await scoped('org-a', () => finish('fresh-install'));
|
||||
if (!fresh.ok) throw new Error('Fresh install failed');
|
||||
expect(fresh.workspace.workspaceId).not.toBe(workspaceId);
|
||||
expect((await scoped('org-a', () => store.list())).workspaces).toEqual([fresh.workspace]);
|
||||
expect(await scoped('org-a', () => store.remove(workspaceId, retired!.revision))).toBe(false);
|
||||
});
|
||||
|
||||
it('allows only one concurrent update of the same organization app revision', async () => {
|
||||
await scoped('org-a', async () => {
|
||||
const current = await store.configureApp(appCredentials, userId);
|
||||
|
|
|
|||
|
|
@ -72,6 +72,8 @@ export interface SlackWorkspaceStorage {
|
|||
read(workspaceId: string): Promise<SlackWorkspaceRecord | null>;
|
||||
metadata(workspaceId: string): Promise<SlackWorkspaceMetadata | null>;
|
||||
disconnect(workspaceId: string, expectedRevision?: string): Promise<boolean>;
|
||||
/** Hide a retired installation while retaining its callback and ownership fences. */
|
||||
remove(workspaceId: string, expectedRevision: string): Promise<boolean>;
|
||||
/** Trusted routing metadata, read only after authenticating the Slack request. */
|
||||
route(appId: string, teamId: string): Promise<SlackWorkspaceMetadata | null>;
|
||||
}
|
||||
|
|
@ -198,7 +200,13 @@ export function createSlackWorkspaceStorage(
|
|||
},
|
||||
{ session },
|
||||
);
|
||||
return changed.matchedCount ? 'removed' : 'conflict';
|
||||
if (!changed.matchedCount) return 'conflict';
|
||||
await workspaces.updateMany(
|
||||
{ appId, tenantId: tenantId ?? null, status: 'disconnected' },
|
||||
{ $set: { removedAt: new Date(), revision: nanoid() } },
|
||||
{ session },
|
||||
);
|
||||
return 'removed';
|
||||
});
|
||||
},
|
||||
async startInstall(input) {
|
||||
|
|
@ -329,7 +337,11 @@ export function createSlackWorkspaceStorage(
|
|||
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
|
||||
throw new TypeError('Invalid Slack workspace page size');
|
||||
const records = await workspaces
|
||||
.find({ tenantId: tenantId ?? null, ...(cursor ? { workspaceId: { $gt: cursor } } : {}) })
|
||||
.find({
|
||||
tenantId: tenantId ?? null,
|
||||
removedAt: { $exists: false },
|
||||
...(cursor ? { workspaceId: { $gt: cursor } } : {}),
|
||||
})
|
||||
.sort({ workspaceId: 1 })
|
||||
.limit(limit + 1)
|
||||
.read('primary')
|
||||
|
|
@ -387,6 +399,19 @@ export function createSlackWorkspaceStorage(
|
|||
return true;
|
||||
});
|
||||
},
|
||||
async remove(workspaceId, expectedRevision) {
|
||||
const removed = await workspaces.updateOne(
|
||||
{
|
||||
workspaceId,
|
||||
tenantId: tenant() ?? null,
|
||||
revision: expectedRevision,
|
||||
status: 'disconnected',
|
||||
removedAt: { $exists: false },
|
||||
},
|
||||
{ $set: { removedAt: new Date(), revision: nanoid() } },
|
||||
);
|
||||
return removed.matchedCount === 1;
|
||||
},
|
||||
async route(appId, teamId) {
|
||||
return runAsSystem(async () => {
|
||||
const record = await workspaces
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { applyTenantIsolation } from './plugins/tenantIsolation';
|
|||
export interface SlackWorkspaceRecord extends SlackWorkspace {
|
||||
encryptedBotToken?: string;
|
||||
installOrder: number;
|
||||
removedAt?: Date;
|
||||
authorityWrites?: number;
|
||||
}
|
||||
|
||||
|
|
@ -54,6 +55,7 @@ export function createSlackWorkspaceModel(
|
|||
encryptedBotToken: { type: String, select: false },
|
||||
installOrder: { type: Number, required: true },
|
||||
authorityWrites: { type: Number, default: 0 },
|
||||
removedAt: Date,
|
||||
},
|
||||
{ timestamps: true },
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue