Secrets: manage roles for database, aws, ssh and generic engines

Registry gains per-engine role kinds with field schemas (database
dynamic and static roles, aws, ssh); unknown engines get a raw JSON
role editor. RolesPanel lists, creates, edits and deletes roles, and
edits write back fields the form does not know about so they are not
dropped. Covered by unit tests and an ssh integration test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-11-09 13:24:50 +00:00
1 parent 6daed8d388
commit 4fa7ff1497
10 files changed
+769 -14

No files matched your search

+10 -5
View File
@@ -1,12 +1,17 @@
import type { BaoClient } from '../../api/bao'
import { engineFor } from '../../api/engines/registry'
import type { Mount } from '../../api/secrets'
import { RolesPanel } from './RolesPanel'
/** Roles / Config / Leases for a dynamic secrets engine. Filled in by later phases. */
export function EngineView({ mount }: { mount: Mount }) {
/** Roles (and, in later phases, Config / Leases) for a dynamic secrets engine. */
export function EngineView({ client, mount }: { client: BaoClient; mount: Mount }) {
const engine = engineFor(mount.type)
return (
<p className="secret-placeholder">
{engine.label} engine at {mount.path}: role management is coming soon.
</p>
<div className="engine-view">
<h2>
{engine.label} · {mount.path}
</h2>
<RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />
</div>
)
}
+121
View File
@@ -0,0 +1,121 @@
import { useId, type FormEvent } from 'react'
import type { FieldDef, RoleKind } from '../../api/engines/registry'
import type { RoleDraft } from '../../api/engines/roles'
function Field({ field, value, onChange }: { field: FieldDef; value: string | boolean; onChange: (v: string | boolean) => void }) {
const helpId = useId()
const help = field.help ? (
<span id={helpId} className="hint">
{field.help}
</span>
) : null
const describedBy = field.help ? helpId : undefined
if (field.type === 'bool') {
return (
<label>
<input type="checkbox" checked={value === true} onChange={(e) => onChange(e.target.checked)} aria-describedby={describedBy} />{' '}
{field.label}
</label>
)
}
if (field.type === 'select') {
return (
<label>
{field.label}
<select value={String(value)} onChange={(e) => onChange(e.target.value)} required={field.required} aria-describedby={describedBy}>
{field.options?.map((o) => (
<option key={o}>{o}</option>
))}
</select>
{help}
</label>
)
}
if (field.type === 'textarea' || field.type === 'statements') {
return (
<label>
{field.label}
<textarea
value={String(value)}
onChange={(e) => onChange(e.target.value)}
rows={field.type === 'statements' ? 5 : 4}
required={field.required}
spellCheck={false}
aria-describedby={describedBy}
/>
{help}
</label>
)
}
return (
<label>
{field.label}
<input
value={String(value)}
onChange={(e) => onChange(e.target.value)}
required={field.required}
placeholder={field.type === 'ttl' ? 'e.g. 1h (optional)' : field.type === 'list' ? 'comma separated' : undefined}
aria-describedby={describedBy}
/>
{help}
</label>
)
}
export function RoleEditor({
kind,
draft,
pending,
error,
onChange,
onSubmit,
onCancel,
}: {
kind: RoleKind
draft: RoleDraft
pending: boolean
error: string | null
onChange: (d: RoleDraft) => void
onSubmit: () => void
onCancel: () => void
}) {
const title = draft.isNew ? `New ${kind.label.toLowerCase()} role` : `Edit ${draft.name}`
function submit(e: FormEvent) {
e.preventDefault()
onSubmit()
}
return (
<form onSubmit={submit} aria-label={title} className="wide">
<h3>{title}</h3>
<label>
Role name
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => onChange({ ...draft, name: e.target.value })} required />
</label>
{kind.fields.length === 0 ? (
<label>
Role (JSON)
<textarea value={draft.json} onChange={(e) => onChange({ ...draft, json: e.target.value })} rows={10} spellCheck={false} />
</label>
) : (
kind.fields.map((f) => (
<Field
key={f.key}
field={f}
value={draft.values[f.key] ?? ''}
onChange={(v) => onChange({ ...draft, values: { ...draft.values, [f.key]: v } })}
/>
))
)}
{error && <p role="alert">{error}</p>}
<div className="form-actions">
<button type="submit" disabled={pending}>
Save
</button>
<button type="button" onClick={onCancel}>
Cancel
</button>
</div>
</form>
)
}
+123
View File
@@ -0,0 +1,123 @@
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 { ENGINES } from '../../api/engines/registry'
import * as roles from '../../api/engines/roles'
import { RolesPanel } from './RolesPanel'
vi.mock('../../api/engines/roles', async (orig) => ({
...(await orig<typeof roles>()),
listRoles: vi.fn(),
readRole: vi.fn(),
writeRole: vi.fn(),
deleteRole: vi.fn(),
}))
const client = new BaoClient('http://b', 't')
function renderPanel(type: keyof typeof ENGINES = 'database') {
return render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<RolesPanel client={client} mount={`${type}/`} engine={ENGINES[type]} />
</QueryClientProvider>,
)
}
beforeEach(() => {
vi.mocked(roles.listRoles).mockResolvedValue(['readonly'])
})
afterEach(() => vi.resetAllMocks())
test('creates a database role from the form', async () => {
vi.mocked(roles.writeRole).mockResolvedValue()
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'New role' }))
await user.type(screen.getByLabelText('Role name'), 'rw')
await user.type(screen.getByLabelText('Database config name'), 'pg')
await user.type(screen.getByLabelText(/^Creation statements/), 'CREATE ROLE "{{{{name}}";')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(roles.writeRole).toHaveBeenCalledWith(
client,
'database/',
ENGINES.database.roleKinds[0],
'rw',
expect.objectContaining({ db_name: 'pg', creation_statements: ['CREATE ROLE "{{name}}";'] }),
)
expect(screen.queryByRole('form')).not.toBeInTheDocument()
})
test('shows validation errors without calling OpenBao', async () => {
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'New role' }))
await user.type(screen.getByLabelText('Role name'), 'rw')
await user.type(screen.getByLabelText('Database config name'), 'pg')
// the statements field is `required` natively, so fill it with whitespace to reach our own check
await user.type(screen.getByLabelText(/^Creation statements/), ' ')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Creation statements is required.')
expect(roles.writeRole).not.toHaveBeenCalled()
})
test('edits an existing role, preserving fields the form does not know', async () => {
vi.mocked(roles.readRole).mockResolvedValue({
db_name: 'pg',
creation_statements: ['CREATE ROLE a;'],
default_ttl: 60,
credential_type: 'password',
})
vi.mocked(roles.writeRole).mockResolvedValue()
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Edit readonly' }))
expect(await screen.findByLabelText('Default TTL')).toHaveValue('60s')
expect(screen.getByLabelText('Role name')).toBeDisabled()
await user.clear(screen.getByLabelText('Default TTL'))
await user.type(screen.getByLabelText('Default TTL'), '2h')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(roles.writeRole).toHaveBeenCalledWith(
client,
'database/',
ENGINES.database.roleKinds[0],
'readonly',
expect.objectContaining({ default_ttl: '2h', credential_type: 'password', db_name: 'pg' }),
)
})
test('deletes a role after confirmation', async () => {
vi.mocked(roles.deleteRole).mockResolvedValue()
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Delete readonly' }))
expect(window.confirm).toHaveBeenCalled()
expect(roles.deleteRole).toHaveBeenCalledWith(client, 'database/', ENGINES.database.roleKinds[0], 'readonly')
})
test('does not delete when the confirmation is declined', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Delete readonly' }))
expect(roles.deleteRole).not.toHaveBeenCalled()
})
test('switches between dynamic and static database roles', async () => {
renderPanel()
const user = userEvent.setup()
await screen.findByRole('table', { name: 'Dynamic roles' })
await user.click(screen.getByRole('tab', { name: 'Static roles' }))
expect(await screen.findByRole('table', { name: 'Static roles' })).toBeInTheDocument()
expect(roles.listRoles).toHaveBeenLastCalledWith(client, 'database/', ENGINES.database.roleKinds[1])
})
test('shows an empty state and the load error', async () => {
vi.mocked(roles.listRoles).mockResolvedValue([])
renderPanel('ssh')
expect(await screen.findByText('No roles yet.')).toBeInTheDocument()
})
+144
View File
@@ -0,0 +1,144 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import type { EngineDef } from '../../api/engines/registry'
import {
deleteRole,
draftFromRole,
emptyDraft,
listRoles,
payloadFromDraft,
readRole,
writeRole,
type RoleDraft,
} from '../../api/engines/roles'
import { ListState } from '../shared/ListState'
import { useConfirm } from '../shared/useConfirm'
import { RoleEditor } from './RoleEditor'
export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
const qc = useQueryClient()
const confirm = useConfirm()
const [kindId, setKindId] = useState(engine.roleKinds[0].id)
const kind = engine.roleKinds.find((k) => k.id === kindId) ?? engine.roleKinds[0]
const [draft, setDraft] = useState<RoleDraft | null>(null)
const [formError, setFormError] = useState<string | null>(null)
const key = ['engine-roles', mount, kind.id]
const roles = useQuery({ queryKey: key, queryFn: () => listRoles(client, mount, kind) })
const save = useMutation({
mutationFn: (d: RoleDraft) => writeRole(client, mount, kind, d.name.trim(), payloadFromDraft(kind, d)),
onSuccess: () => {
setDraft(null)
return qc.invalidateQueries({ queryKey: key })
},
})
const remove = useMutation({
mutationFn: (name: string) => deleteRole(client, mount, kind, name),
onSuccess: () => qc.invalidateQueries({ queryKey: key }),
})
const edit = useMutation({
mutationFn: (name: string) => readRole(client, mount, kind, name).then((data) => draftFromRole(kind, name, data)),
onSuccess: (d) => {
setFormError(null)
setDraft(d)
},
})
const switchKind = (id: string) => {
setKindId(id)
setDraft(null)
save.reset()
}
return (
<section aria-label="Roles">
{engine.roleKinds.length > 1 && (
<div role="tablist" aria-label="Role type" className="tabs">
{engine.roleKinds.map((k) => (
<button key={k.id} type="button" role="tab" aria-selected={k.id === kind.id} onClick={() => switchKind(k.id)}>
{k.label}
</button>
))}
</div>
)}
<ListState query={roles} empty={`No ${kind.label.toLowerCase()} yet.`} />
{!!roles.data?.length && (
<table aria-label={kind.label}>
<thead>
<tr>
<th>Role</th>
<th />
</tr>
</thead>
<tbody>
{roles.data.map((name) => (
<tr key={name}>
<td>{name}</td>
<td>
<button type="button" aria-label={`Edit ${name}`} onClick={() => edit.mutate(name)}>
Edit
</button>
<button
type="button"
aria-label={`Delete ${name}`}
onClick={async () => {
if (
await confirm({
title: `Delete role “${name}”?`,
message: 'Credentials already issued from it stay valid until their leases end.',
confirmLabel: 'Delete',
})
)
remove.mutate(name)
}}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{remove.error && <p role="alert">{remove.error.message}</p>}
{edit.error && <p role="alert">{edit.error.message}</p>}
{!draft && (
<button
type="button"
onClick={() => {
setFormError(null)
save.reset()
setDraft(emptyDraft(kind))
}}
>
New role
</button>
)}
{draft && (
<RoleEditor
kind={kind}
draft={draft}
pending={save.isPending}
error={formError ?? save.error?.message ?? null}
onChange={setDraft}
onSubmit={() => {
setFormError(null)
try {
payloadFromDraft(kind, draft)
} catch (e) {
setFormError((e as Error).message)
return
}
save.mutate(draft)
}}
onCancel={() => {
setDraft(null)
save.reset()
}}
/>
)}
</section>
)
}
+3 -1
View File
@@ -133,6 +133,7 @@ test('groups mounts by engine and shows the engine view for a dynamic mount', as
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'cubbyhole/', type: 'cubbyhole' },
])
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<SessionProvider>
@@ -151,7 +152,8 @@ test('groups mounts by engine and shows the engine view for a dynamic mount', as
expect(within(select).queryByText('cubbyhole/')).not.toBeInTheDocument()
await user.selectOptions(select, 'database/')
expect(await screen.findByText(/Database engine at database\//)).toBeInTheDocument()
expect(await screen.findByRole('heading', { name: /Database · database\// })).toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'New role' })).toBeInTheDocument()
expect(api.listSecrets).not.toHaveBeenCalled()
})
+1 -1
View File
@@ -74,7 +74,7 @@ function Browser({ client }: { client: BaoClient }) {
{mountSelect}
</nav>
</div>
<EngineView mount={current} />
<EngineView client={client} mount={current} />
</div>
)
}