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

+112 -7
View File
@@ -1,19 +1,124 @@
import type { Mount } from '../secrets'
import { isKvV2 } from '../secrets'
/** Describes a dynamic secrets engine the UI can manage. Grows in later phases (role fields, creds, config). */
export type FieldType =
/** Single-line string. */
| 'text'
/** Multi-line string sent as-is (e.g. a JSON policy document). */
| 'textarea'
/** Duration such as "1h" or "3600s"; read back from OpenBao as seconds. */
| 'ttl'
/** Comma or newline separated values sent as a string array. */
| 'list'
/** Statements separated by blank lines (SQL can contain commas) sent as a string array. */
| 'statements'
| 'bool'
| 'select'
export interface FieldDef {
key: string
label: string
type: FieldType
required?: boolean
options?: string[]
help?: string
}
/** One family of roles under a mount, e.g. database "roles" and "static-roles". */
export interface RoleKind {
id: string
label: string
/** Path relative to the mount that roles are listed and written under. */
path: string
/** Empty means the role is edited as raw JSON (generic engines). */
fields: FieldDef[]
}
/** Describes a dynamic secrets engine the UI can manage. Grows in later phases (creds, config). */
export interface EngineDef {
/** Engine type as reported by sys/mounts. */
type: string
label: string
/** Path, relative to the mount, that roles are listed/written under. */
rolesPath: string
roleKinds: RoleKind[]
}
const DATABASE_ROLE: RoleKind = {
id: 'roles',
label: 'Dynamic roles',
path: 'roles',
fields: [
{ key: 'db_name', label: 'Database config name', type: 'text', required: true },
{
key: 'creation_statements',
label: 'Creation statements',
type: 'statements',
required: true,
help: 'Separate statements with a blank line. Use {{name}}, {{password}} and {{expiration}}.',
},
{ key: 'revocation_statements', label: 'Revocation statements', type: 'statements' },
{ key: 'renew_statements', label: 'Renew statements', type: 'statements' },
{ key: 'rollback_statements', label: 'Rollback statements', type: 'statements' },
{ key: 'default_ttl', label: 'Default TTL', type: 'ttl' },
{ key: 'max_ttl', label: 'Max TTL', type: 'ttl' },
],
}
const DATABASE_STATIC_ROLE: RoleKind = {
id: 'static-roles',
label: 'Static roles',
path: 'static-roles',
fields: [
{ key: 'db_name', label: 'Database config name', type: 'text', required: true },
{ key: 'username', label: 'Database username', type: 'text', required: true },
{ key: 'rotation_statements', label: 'Rotation statements', type: 'statements' },
{ key: 'rotation_period', label: 'Rotation period', type: 'ttl' },
],
}
const AWS_ROLE: RoleKind = {
id: 'roles',
label: 'Roles',
path: 'roles',
fields: [
{
key: 'credential_type',
label: 'Credential type',
type: 'select',
required: true,
options: ['iam_user', 'assumed_role', 'federation_token'],
},
{ key: 'role_arns', label: 'Role ARNs', type: 'list', help: 'For assumed_role.' },
{ key: 'policy_arns', label: 'Policy ARNs', type: 'list' },
{ key: 'policy_document', label: 'Policy document (JSON)', type: 'textarea' },
{ key: 'iam_groups', label: 'IAM groups', type: 'list', help: 'For iam_user.' },
{ key: 'default_sts_ttl', label: 'Default STS TTL', type: 'ttl' },
{ key: 'max_sts_ttl', label: 'Max STS TTL', type: 'ttl' },
{ key: 'permissions_boundary_arn', label: 'Permissions boundary ARN', type: 'text' },
{ key: 'user_path', label: 'IAM user path', type: 'text' },
],
}
const SSH_ROLE: RoleKind = {
id: 'roles',
label: 'Roles',
path: 'roles',
fields: [
{ key: 'key_type', label: 'Key type', type: 'select', required: true, options: ['ca', 'otp'] },
{ key: 'default_user', label: 'Default user', type: 'text' },
{ key: 'allowed_users', label: 'Allowed users', type: 'text', help: 'Comma separated; * allows any.' },
{ key: 'cidr_list', label: 'CIDR list', type: 'text', help: 'otp only. Comma separated.' },
{ key: 'ttl', label: 'TTL', type: 'ttl' },
{ key: 'max_ttl', label: 'Max TTL', type: 'ttl' },
{ key: 'allow_user_certificates', label: 'Allow user certificates', type: 'bool' },
{ key: 'allow_host_certificates', label: 'Allow host certificates', type: 'bool' },
{ key: 'allowed_extensions', label: 'Allowed extensions', type: 'text' },
],
}
export const ENGINES: Record<string, EngineDef> = {
database: { type: 'database', label: 'Database', rolesPath: 'roles' },
aws: { type: 'aws', label: 'AWS', rolesPath: 'roles' },
ssh: { type: 'ssh', label: 'SSH', rolesPath: 'roles' },
database: { type: 'database', label: 'Database', roleKinds: [DATABASE_ROLE, DATABASE_STATIC_ROLE] },
aws: { type: 'aws', label: 'AWS', roleKinds: [AWS_ROLE] },
ssh: { type: 'ssh', label: 'SSH', roleKinds: [SSH_ROLE] },
}
/** Engine types that are managed as plain secret stores or by the system, not as dynamic engines. */
@@ -21,7 +126,7 @@ const NOT_DYNAMIC = new Set(['kv', 'generic', 'cubbyhole', 'system', 'identity']
/** Known engine definition, or a generic fallback (raw JSON roles) for any other dynamic engine type. */
export function engineFor(type: string): EngineDef {
return ENGINES[type] ?? { type, label: type, rolesPath: 'roles' }
return ENGINES[type] ?? { type, label: type, roleKinds: [{ id: 'roles', label: 'Roles', path: 'roles', fields: [] }] }
}
export type MountKind = 'kv' | 'dynamic'
+49
View File
@@ -0,0 +1,49 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { BaoClient } from '../bao'
import { listMounts } from '../secrets'
import { ENGINES } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const mount = `it-ssh-${sfx}/`
const kind = ENGINES.ssh.roleKinds[0]
beforeAll(async () => {
await client.request('POST', `sys/mounts/${mount.slice(0, -1)}`, { type: 'ssh' })
})
afterAll(async () => {
await client.request('DELETE', `sys/mounts/${mount.slice(0, -1)}`).catch(() => {})
})
describe('dynamic engine roles (ssh)', () => {
test('the new mount is listed with its type', async () => {
const m = (await listMounts(client)).find((x) => x.path === mount)
expect(m?.type).toBe('ssh')
})
test('creates, lists, edits and deletes a role through the form model', async () => {
expect(await listRoles(client, mount, kind)).toEqual([])
const draft = emptyDraft(kind)
draft.values.key_type = 'ca'
draft.values.allowed_users = 'alice,bob'
draft.values.ttl = '30m'
draft.values.allow_user_certificates = true
await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, draft))
expect(await listRoles(client, mount, kind)).toEqual(['ops'])
const read = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops'))
expect(read.values).toMatchObject({ key_type: 'ca', allowed_users: 'alice,bob', ttl: '1800s', allow_user_certificates: true })
// an edit writes the whole role back, so values it did not touch must survive
read.values.max_ttl = '2h'
await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, read))
const again = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops'))
expect(again.values).toMatchObject({ allowed_users: 'alice,bob', ttl: '1800s', max_ttl: '7200s' })
await deleteRole(client, mount, kind, 'ops')
expect(await listRoles(client, mount, kind)).toEqual([])
})
})
+101
View File
@@ -0,0 +1,101 @@
import { expect, test, vi } from 'vitest'
import { BaoClient } from '../bao'
import { ENGINES, engineFor, mountKind } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
const dbRole = ENGINES.database.roleKinds[0]
const awsRole = ENGINES.aws.roleKinds[0]
const sshRole = ENGINES.ssh.roleKinds[0]
test('classifies mounts', () => {
expect(mountKind({ path: 'secret/', type: 'kv', version: '2' })).toBe('kv')
expect(mountKind({ path: 'old/', type: 'kv', version: '1' })).toBeNull()
expect(mountKind({ path: 'cubbyhole/', type: 'cubbyhole' })).toBeNull()
expect(mountKind({ path: 'database/', type: 'database' })).toBe('dynamic')
expect(mountKind({ path: 'pki/', type: 'pki' })).toBe('dynamic')
})
test('unknown engines fall back to a raw JSON role editor', () => {
const e = engineFor('pki')
expect(e.label).toBe('pki')
expect(e.roleKinds[0].fields).toEqual([])
})
test('database role round-trips through the form, keeping unknown fields', () => {
const data = {
db_name: 'pg',
creation_statements: ['CREATE ROLE "{{name}}" LOGIN;', 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";'],
default_ttl: 3600,
max_ttl: 0,
credential_type: 'password',
}
const draft = draftFromRole(dbRole, 'ro', data)
expect(draft.values.default_ttl).toBe('3600s')
expect(draft.values.max_ttl).toBe('')
expect(draft.extras).toEqual({ credential_type: 'password' })
draft.values.max_ttl = '24h'
expect(payloadFromDraft(dbRole, draft)).toEqual({
db_name: 'pg',
creation_statements: data.creation_statements,
revocation_statements: [],
renew_statements: [],
rollback_statements: [],
default_ttl: '3600s',
max_ttl: '24h',
credential_type: 'password',
})
})
test('statements split on blank lines, lists on commas or newlines', () => {
const d = emptyDraft(dbRole)
d.values.db_name = 'pg'
d.values.creation_statements = 'CREATE ROLE a,\n LOGIN;\n\nGRANT x;'
expect(payloadFromDraft(dbRole, d).creation_statements).toEqual(['CREATE ROLE a,\n LOGIN;', 'GRANT x;'])
const a = emptyDraft(awsRole)
a.values.policy_arns = 'arn:1, arn:2\narn:3'
expect(payloadFromDraft(awsRole, a).policy_arns).toEqual(['arn:1', 'arn:2', 'arn:3'])
})
test('required fields are enforced', () => {
expect(() => payloadFromDraft(dbRole, emptyDraft(dbRole))).toThrow('Database config name is required.')
const d = emptyDraft(dbRole)
d.values.db_name = 'pg'
expect(() => payloadFromDraft(dbRole, d)).toThrow('Creation statements is required.')
})
test('select defaults to the first option and booleans are sent as booleans', () => {
const d = emptyDraft(sshRole)
expect(d.values.key_type).toBe('ca')
d.values.allow_user_certificates = true
const body = payloadFromDraft(sshRole, d)
expect(body).toMatchObject({ key_type: 'ca', allow_user_certificates: true, allow_host_certificates: false })
expect(body).not.toHaveProperty('ttl')
})
test('generic roles are raw JSON and must be objects', () => {
const kind = engineFor('pki').roleKinds[0]
const d = emptyDraft(kind)
d.json = '{"allowed_domains":"example.com"}'
expect(payloadFromDraft(kind, d)).toEqual({ allowed_domains: 'example.com' })
d.json = '{nope'
expect(() => payloadFromDraft(kind, d)).toThrow('not valid JSON')
d.json = '[]'
expect(() => payloadFromDraft(kind, d)).toThrow('must be a JSON object')
})
test('role API calls use the mount, kind path and an encoded name', async () => {
const c = new BaoClient('http://b', 't')
const req = vi.spyOn(c, 'request').mockResolvedValue({ data: { db_name: 'pg' } })
vi.spyOn(c, 'list').mockResolvedValue(['b', 'a'])
expect(await listRoles(c, 'database/', dbRole)).toEqual(['a', 'b'])
expect(c.list).toHaveBeenCalledWith('database/roles')
expect(await readRole(c, 'database/', dbRole, 'my role')).toEqual({ db_name: 'pg' })
expect(req).toHaveBeenCalledWith('GET', 'database/roles/my%20role')
await writeRole(c, 'database/', dbRole, 'ro', { db_name: 'pg' })
expect(req).toHaveBeenCalledWith('POST', 'database/roles/ro', { db_name: 'pg' })
await deleteRole(c, 'database/', ENGINES.database.roleKinds[1], 'svc')
expect(req).toHaveBeenCalledWith('DELETE', 'database/static-roles/svc')
})
+105
View File
@@ -0,0 +1,105 @@
import type { BaoClient } from '../bao'
import type { FieldDef, RoleKind } from './registry'
const enc = encodeURIComponent
export type RoleData = Record<string, unknown>
export type DraftValue = string | boolean
export interface RoleDraft {
name: string
isNew: boolean
/** Values for the schema fields, keyed by field key. */
values: Record<string, DraftValue>
/** Raw JSON body, used when the role kind has no field schema. */
json: string
/** Fields OpenBao returned that the schema does not know about; written back unchanged so edits don't drop them. */
extras: RoleData
}
export async function listRoles(c: BaoClient, mount: string, kind: RoleKind): Promise<string[]> {
return (await c.list(`${mount}${kind.path}`)).sort((a, b) => a.localeCompare(b))
}
export async function readRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise<RoleData> {
const res = await c.request<{ data: RoleData }>('GET', `${mount}${kind.path}/${enc(name)}`)
return res.data
}
export async function writeRole(c: BaoClient, mount: string, kind: RoleKind, name: string, body: RoleData): Promise<void> {
await c.request('POST', `${mount}${kind.path}/${enc(name)}`, body)
}
export async function deleteRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise<void> {
await c.request('DELETE', `${mount}${kind.path}/${enc(name)}`)
}
const listText = (v: unknown, sep: string) => (Array.isArray(v) ? v.join(sep) : typeof v === 'string' ? v : '')
function fieldToDraft(f: FieldDef, v: unknown): DraftValue {
switch (f.type) {
case 'bool':
return v === true
case 'ttl':
// OpenBao reports durations as seconds; 0 means "unset / use default".
return typeof v === 'number' ? (v > 0 ? `${v}s` : '') : typeof v === 'string' ? v : ''
case 'list':
return listText(v, ', ')
case 'statements':
return listText(v, '\n\n')
default:
return typeof v === 'string' ? v : v == null ? '' : String(v)
}
}
export function emptyDraft(kind: RoleKind): RoleDraft {
const values: Record<string, DraftValue> = {}
for (const f of kind.fields) values[f.key] = f.type === 'bool' ? false : f.type === 'select' ? (f.options?.[0] ?? '') : ''
return { name: '', isNew: true, values, json: '{\n}', extras: {} }
}
export function draftFromRole(kind: RoleKind, name: string, data: RoleData): RoleDraft {
const known = new Set(kind.fields.map((f) => f.key))
const values: Record<string, DraftValue> = {}
for (const f of kind.fields) values[f.key] = fieldToDraft(f, data[f.key])
const extras = Object.fromEntries(Object.entries(data).filter(([k]) => !known.has(k)))
return { name, isNew: false, values, json: JSON.stringify(data, null, 2), extras }
}
const splitList = (s: string) =>
s
.split(/[,\n]/)
.map((x) => x.trim())
.filter(Boolean)
const splitStatements = (s: string) =>
s
.split(/\n\s*\n/)
.map((x) => x.trim())
.filter(Boolean)
/** Request body for a role write. Throws an Error with a user-facing message for invalid input. */
export function payloadFromDraft(kind: RoleKind, draft: RoleDraft): RoleData {
if (kind.fields.length === 0) {
let parsed: unknown
try {
parsed = JSON.parse(draft.json)
} catch {
throw new Error('Role body is not valid JSON.')
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Role body must be a JSON object.')
return parsed as RoleData
}
const body: RoleData = { ...draft.extras }
for (const f of kind.fields) {
const v = draft.values[f.key]
if (f.type === 'bool') body[f.key] = v === true
else if (f.type === 'list') body[f.key] = splitList(String(v))
else if (f.type === 'statements') body[f.key] = splitStatements(String(v))
else if (String(v).trim() !== '') body[f.key] = String(v).trim()
else if (f.required) throw new Error(`${f.label} is required.`)
else delete body[f.key]
if ((f.type === 'list' || f.type === 'statements') && f.required && (body[f.key] as string[]).length === 0) {
throw new Error(`${f.label} is required.`)
}
}
return body
}
+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>
)
}