Secrets: delete a secrets engine with a typed confirmation

The delete panel counts what will be lost (KV entries, or roles and
leases for dynamic engines), lists the policies that still grant access
under the mount, and keeps Delete disabled until the mount path is
typed. Anything it can't count is said so rather than hidden. Switching
mounts closes the panel, and the deleted mount's cached data is dropped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-11-09 14:25:21 +00:00
1 parent 13a5353868
commit 1b3f6e4de5
4 files changed
+307 -3

No files matched your search

@@ -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<typeof mounts>()), 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(
<QueryClientProvider client={qc}>
<DeleteMountDialog client={client} mount={mount} onClose={onClose} onDeleted={onDeleted} />
</QueryClientProvider>,
)
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'])
})
+105
View File
@@ -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 (
<p>
Every secret stored in <code>{mount.path}</code>, with all of its versions, will be permanently deleted
{impact.topLevelEntries !== undefined && <> (at least {plural(impact.topLevelEntries, 'entry', 'entries')} at the top level)</>}.
</p>
)
}
return (
<p>
The {engineFor(mount.type).label} engine at <code>{mount.path}</code> 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.' : ''}
</p>
)
}
/**
* 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 (
<section role="alertdialog" aria-label={`Delete ${mount.path}`} className="mount-dialog mount-delete">
<h3>Delete {mount.path}?</h3>
{impact.isPending && <p role="status">Checking what is in it…</p>}
{impact.error && <p role="alert">{impact.error.message}</p>}
{impact.data && <Consequences mount={mount} impact={impact.data} />}
{impact.data && impact.data.unknown.length > 0 && (
<p className="hint">Could not count {impact.data.unknown.join(', ')}, so there may be more than shown.</p>
)}
<p>This cannot be undone.</p>
{referencing.length > 0 && (
<>
<p>
{plural(referencing.length, 'policy', 'policies')} grant{referencing.length === 1 ? 's' : ''} access under this mount.
They are not changed, and will point at nothing:
</p>
<NameChips names={referencing} />
</>
)}
{access.error && <p className="hint">Could not check which policies refer to this mount: {access.error.message}</p>}
<form onSubmit={submit} aria-label={`Confirm deleting ${mount.path}`}>
<label htmlFor={inputId}>
Type <code>{mount.path}</code> to confirm
</label>
<input id={inputId} value={typed} onChange={(e) => setTyped(e.target.value)} autoComplete="off" spellCheck={false} />
{remove.error && <p role="alert">{remove.error.message}</p>}
<div className="form-actions">
<button type="submit" disabled={!confirmed || remove.isPending}>
Delete forever
</button>
<button type="button" onClick={onClose}>
Cancel
</button>
</div>
</form>
</section>
)
}
+35 -1
View File
@@ -17,7 +17,7 @@ vi.mock('../../api/grants')
vi.mock('../../api/identities')
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof api>()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() }))
vi.mock('../../api/tokens')
vi.mock('../../api/mounts', async (orig) => ({ ...(await orig<typeof mountsApi>()), createMount: vi.fn(), tuneMount: vi.fn(), readKvConfig: vi.fn() }))
vi.mock('../../api/mounts', async (orig) => ({ ...(await orig<typeof mountsApi>()), 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(
<QueryClientProvider client={new QueryClient()}>
+23 -2
View File
@@ -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<string | null>(null)
const [prefix, setPrefix] = useState('')
const [selected, setSelected] = useState<string | null>(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
</button>
)}
{current && (
<button type="button" onClick={() => setDialog(dialog === 'delete' ? null : 'delete')} aria-expanded={dialog === 'delete'}>
Delete
</button>
)}
</div>
)
const dialogs = dialog && (
const dialogs = dialog === 'delete' && current ? (
<DeleteMountDialog
key={current.path}
client={client}
mount={current}
onClose={closeDialog}
onDeleted={() => {
closeDialog()
// Fall back to the first remaining mount.
setMount(null)
go('')
}}
/>
) : dialog && dialog !== 'delete' && (
<MountDialog
// Remount per mount so one mount's settings are never shown (or saved) for another.
key={dialog === 'edit' ? current?.path : 'create'}
@@ -87,6 +106,8 @@ function Browser({ client }: { client: BaoClient }) {
onChange={(e) => {
setMount(e.target.value)
go('')
// A settings or delete panel belongs to the mount it was opened for.
setDialog(null)
}}
>
{kv.length > 0 && (