diff --git a/src/features/secrets/DeleteMountDialog.test.tsx b/src/features/secrets/DeleteMountDialog.test.tsx new file mode 100644 index 0000000..35c6574 --- /dev/null +++ b/src/features/secrets/DeleteMountDialog.test.tsx @@ -0,0 +1,144 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { BaoClient } from '../../api/bao' +import * as mounts from '../../api/mounts' +import type { Mount } from '../../api/secrets' +import { DeleteMountDialog } from './DeleteMountDialog' + +vi.mock('../../api/mounts', async (orig) => ({ ...(await orig()), deleteMount: vi.fn(), mountImpact: vi.fn() })) +vi.mock('../shared/useAccessInputs', () => ({ useAccessInputs: vi.fn() })) + +import { useAccessInputs } from '../shared/useAccessInputs' + +const client = new BaoClient('http://b', 't') +const kv: Mount = { path: 'secret/', type: 'kv', version: '2' } +const db: Mount = { path: 'database/', type: 'database' } + +function policies(list: { name: string; hcl: string | null }[], error: Error | null = null) { + vi.mocked(useAccessInputs).mockReturnValue({ data: error ? undefined : { identities: [], policies: list, notes: [] }, error } as never) +} + +beforeEach(() => policies([])) +afterEach(() => vi.resetAllMocks()) + +function setup(mount: Mount) { + const onClose = vi.fn() + const onDeleted = vi.fn() + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + , + ) + return { user: userEvent.setup(), onClose, onDeleted, qc } +} + +const deleteButton = () => screen.getByRole('button', { name: 'Delete forever' }) + +test('describes what deleting a KV store destroys', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 4, unknown: [] }) + setup(kv) + expect(await screen.findByText(/with all of its versions, will be permanently deleted/)).toHaveTextContent('at least 4 entries at the top level') + expect(screen.getByText('This cannot be undone.')).toBeInTheDocument() + expect(mounts.mountImpact).toHaveBeenCalledWith(client, 'secret/', 'kv') +}) + +test('describes a dynamic engine, including that leases are revoked', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 1, hasLeases: true, unknown: [] }) + setup(db) + const text = await screen.findByText(/engine at/) + expect(text).toHaveTextContent('Database engine at database/ will be permanently deleted, with its 1 role and its configuration.') + expect(text).toHaveTextContent('Every lease it has issued will be revoked') +}) + +test('does not claim leases are revoked when there are none', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] }) + setup(db) + expect(await screen.findByText(/engine at/)).not.toHaveTextContent('lease') +}) + +test('says what it could not count', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 2, hasLeases: undefined, unknown: ['leases'] }) + setup(db) + expect(await screen.findByText('Could not count leases, so there may be more than shown.')).toBeInTheDocument() +}) + +test('lists policies that refer to the mount and leaves them alone', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + policies([ + { name: 'envbao-user-alice', hcl: 'path "secret/data/team-a/*" { capabilities = ["read"] }' }, + { name: 'unrelated', hcl: 'path "other/x" { capabilities = ["read"] }' }, + ]) + setup(kv) + expect(await screen.findByText(/1 policy grants access under this mount/)).toBeInTheDocument() + expect(screen.getByText('envbao-user-alice')).toBeInTheDocument() + expect(screen.queryByText('unrelated')).not.toBeInTheDocument() +}) + +test('says when policies could not be checked', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + policies([], new Error('permission denied')) + setup(kv) + expect(await screen.findByText(/Could not check which policies refer to this mount: permission denied/)).toBeInTheDocument() +}) + +test('Delete stays disabled until the path is typed, and nothing is deleted before then', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + const { user } = setup(kv) + expect(deleteButton()).toBeDisabled() + await user.type(screen.getByLabelText(/Type/), 'secre') + expect(deleteButton()).toBeDisabled() + await user.type(screen.getByLabelText(/Type/), 'x') + expect(deleteButton()).toBeDisabled() + expect(mounts.deleteMount).not.toHaveBeenCalled() +}) + +test.each(['secret/', 'secret', ' secret/ '])('deleting after typing "%s"', async (typed) => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + vi.mocked(mounts.deleteMount).mockResolvedValue() + const { user, onDeleted } = setup(kv) + await user.type(screen.getByLabelText(/Type/), typed) + await user.click(deleteButton()) + expect(mounts.deleteMount).toHaveBeenCalledWith(client, 'secret/') + expect(onDeleted).toHaveBeenCalled() +}) + +test('a different mount name does not unlock it', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + const { user } = setup(kv) + await user.type(screen.getByLabelText(/Type/), 'secrets') + expect(deleteButton()).toBeDisabled() +}) + +test('shows the server error and stays open', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + vi.mocked(mounts.deleteMount).mockRejectedValue(new Error('permission denied')) + const { user, onDeleted } = setup(kv) + await user.type(screen.getByLabelText(/Type/), 'secret') + await user.click(deleteButton()) + expect(await screen.findByRole('alert')).toHaveTextContent('permission denied') + expect(onDeleted).not.toHaveBeenCalled() +}) + +test('cancel closes without deleting', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + const { user, onClose } = setup(kv) + await user.click(screen.getByRole('button', { name: 'Cancel' })) + expect(onClose).toHaveBeenCalled() + expect(mounts.deleteMount).not.toHaveBeenCalled() +}) + +test('forgets cached data for the deleted mount', async () => { + vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] }) + vi.mocked(mounts.deleteMount).mockResolvedValue() + const { user, qc } = setup(db) + qc.setQueryData(['engine-roles', 'database/', 'roles'], ['ro']) + qc.setQueryData(['engine-roles', 'ssh/', 'roles'], ['keep']) + await user.type(screen.getByLabelText(/Type/), 'database') + await user.click(deleteButton()) + await vi.waitFor(() => expect(mounts.deleteMount).toHaveBeenCalled()) + await vi.waitFor(() => expect(qc.getQueryData(['engine-roles', 'database/', 'roles'])).toBeUndefined()) + expect(qc.getQueryData(['engine-roles', 'ssh/', 'roles'])).toEqual(['keep']) +}) diff --git a/src/features/secrets/DeleteMountDialog.tsx b/src/features/secrets/DeleteMountDialog.tsx new file mode 100644 index 0000000..a27f6c0 --- /dev/null +++ b/src/features/secrets/DeleteMountDialog.tsx @@ -0,0 +1,105 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useId, useState, type FormEvent } from 'react' +import type { BaoClient } from '../../api/bao' +import { engineFor } from '../../api/engines/registry' +import { deleteMount, mountImpact, type MountImpact } from '../../api/mounts' +import type { Mount } from '../../api/secrets' +import { policiesReferencing } from '../../model/mounts' +import { useAccessInputs } from '../shared/useAccessInputs' +import { NameChips } from '../shared/PolicyChips' + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}` + +function Consequences({ mount, impact }: { mount: Mount; impact: MountImpact }) { + if (impact.kind === 'kv') { + return ( +

+ Every secret stored in {mount.path}, with all of its versions, will be permanently deleted + {impact.topLevelEntries !== undefined && <> (at least {plural(impact.topLevelEntries, 'entry', 'entries')} at the top level)}. +

+ ) + } + return ( +

+ The {engineFor(mount.type).label} engine at {mount.path} will be permanently deleted + {impact.roles !== undefined && <>, with its {plural(impact.roles, 'role')} and its configuration}. + {impact.hasLeases ? ' Every lease it has issued will be revoked, so credentials already handed out stop working.' : ''} +

+ ) +} + +/** + * Deleting a mount destroys its data and revokes its leases, so the button stays disabled until the path is typed. + * Policies that mention the mount are listed, not changed: they are left in place. + */ +export function DeleteMountDialog({ client, mount, onClose, onDeleted }: { + client: BaoClient + mount: Mount + onClose: () => void + onDeleted: () => void +}) { + const qc = useQueryClient() + const inputId = useId() + const [typed, setTyped] = useState('') + const impact = useQuery({ + queryKey: ['mount-impact', mount.path], + queryFn: () => mountImpact(client, mount.path, mount.type), + gcTime: 0, + staleTime: 0, + }) + const access = useAccessInputs(client) + const referencing = access.data ? policiesReferencing(access.data.policies, mount.path) : [] + const confirmed = typed.trim().replace(/\/+$/, '') === mount.path.replace(/\/+$/, '') + + const remove = useMutation({ + mutationFn: () => deleteMount(client, mount.path), + onSuccess: async () => { + qc.removeQueries({ predicate: (q) => ['kv-list', 'engine-roles', 'engine-config', 'leases', 'mount-impact', 'kv-config'].includes(String(q.queryKey[0])) && q.queryKey[1] === mount.path }) + await qc.invalidateQueries({ queryKey: ['mounts'] }) + onDeleted() + }, + }) + + function submit(e: FormEvent) { + e.preventDefault() + if (confirmed) remove.mutate() + } + + return ( +
+

Delete {mount.path}?

+ {impact.isPending &&

Checking what is in it…

} + {impact.error &&

{impact.error.message}

} + {impact.data && } + {impact.data && impact.data.unknown.length > 0 && ( +

Could not count {impact.data.unknown.join(', ')}, so there may be more than shown.

+ )} +

This cannot be undone.

+ {referencing.length > 0 && ( + <> +

+ {plural(referencing.length, 'policy', 'policies')} grant{referencing.length === 1 ? 's' : ''} access under this mount. + They are not changed, and will point at nothing: +

+ + + )} + {access.error &&

Could not check which policies refer to this mount: {access.error.message}

} +
+ + setTyped(e.target.value)} autoComplete="off" spellCheck={false} /> + {remove.error &&

{remove.error.message}

} +
+ + +
+
+
+ ) +} diff --git a/src/features/secrets/SecretsPage.test.tsx b/src/features/secrets/SecretsPage.test.tsx index bf31ec3..16948ec 100644 --- a/src/features/secrets/SecretsPage.test.tsx +++ b/src/features/secrets/SecretsPage.test.tsx @@ -17,7 +17,7 @@ vi.mock('../../api/grants') vi.mock('../../api/identities') vi.mock('../../api/secrets', async (orig) => ({ ...(await orig()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() })) vi.mock('../../api/tokens') -vi.mock('../../api/mounts', async (orig) => ({ ...(await orig()), createMount: vi.fn(), tuneMount: vi.fn(), readKvConfig: vi.fn() })) +vi.mock('../../api/mounts', async (orig) => ({ ...(await orig()), createMount: vi.fn(), tuneMount: vi.fn(), readKvConfig: vi.fn(), deleteMount: vi.fn(), mountImpact: vi.fn() })) const client = new BaoClient('http://b', 't') @@ -214,6 +214,40 @@ test('Settings opens the selected mount\'s settings, and toggles closed', async expect(screen.queryByRole('region', { name: 'Settings for secret/' })).not.toBeInTheDocument() }) +test('deleting the selected engine falls back to another', async () => { + vi.mocked(api.listMounts).mockResolvedValue([ + { path: 'secret/', type: 'kv', version: '2' }, + { path: 'hosts/', type: 'ssh' }, + ]) + vi.mocked(mountsApi.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] }) + vi.mocked(mountsApi.deleteMount).mockResolvedValue() + vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([]) + const user = await openPage() + await user.selectOptions(await screen.findByLabelText('Mount'), 'hosts/') + await user.click(screen.getByRole('button', { name: 'Delete' })) + expect(await screen.findByRole('alertdialog', { name: 'Delete hosts/' })).toBeInTheDocument() + vi.mocked(api.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }]) + await user.type(screen.getByLabelText(/Type/), 'hosts') + await user.click(screen.getByRole('button', { name: 'Delete forever' })) + expect(mountsApi.deleteMount).toHaveBeenCalledWith(client, 'hosts/') + expect(await screen.findByRole('button', { name: 'secret/' })).toBeInTheDocument() + expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument() +}) + +test('switching mounts closes an open delete panel', async () => { + vi.mocked(api.listMounts).mockResolvedValue([ + { path: 'secret/', type: 'kv', version: '2' }, + { path: 'hosts/', type: 'ssh' }, + ]) + vi.mocked(mountsApi.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] }) + vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([]) + const user = await openPage() + await user.click(await screen.findByRole('button', { name: 'Delete' })) + expect(await screen.findByRole('alertdialog', { name: 'Delete secret/' })).toBeInTheDocument() + await user.selectOptions(screen.getByLabelText('Mount'), 'hosts/') + expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument() +}) + test('asks to connect first', () => { render( diff --git a/src/features/secrets/SecretsPage.tsx b/src/features/secrets/SecretsPage.tsx index 76799d3..1cec9ab 100644 --- a/src/features/secrets/SecretsPage.tsx +++ b/src/features/secrets/SecretsPage.tsx @@ -6,6 +6,7 @@ import { listSecrets } from '../../api/secrets' import { RequireConnection } from '../shared/RequireConnection' import { useMounts } from '../shared/useMounts' import { AccessPanel } from './AccessPanel' +import { DeleteMountDialog } from './DeleteMountDialog' import { EngineView } from './EngineView' import { MountDialog } from './MountDialog' @@ -14,7 +15,7 @@ function Browser({ client }: { client: BaoClient }) { const [mountChoice, setMount] = useState(null) const [prefix, setPrefix] = useState('') const [selected, setSelected] = useState(null) - const [dialog, setDialog] = useState<'create' | 'edit' | null>(null) + const [dialog, setDialog] = useState<'create' | 'edit' | 'delete' | null>(null) const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0] ?? null const mount = current?.path ?? null @@ -46,9 +47,27 @@ function Browser({ client }: { client: BaoClient }) { Settings )} + {current && ( + + )} ) - const dialogs = dialog && ( + const dialogs = dialog === 'delete' && current ? ( + { + closeDialog() + // Fall back to the first remaining mount. + setMount(null) + go('') + }} + /> + ) : dialog && dialog !== 'delete' && ( { setMount(e.target.value) go('') + // A settings or delete panel belongs to the mount it was opened for. + setDialog(null) }} > {kv.length > 0 && (