Secrets: engine config editors and one-time credential generation
Adds Config tab (database connections with rotate/reset, aws root and lease, ssh CA with generate/import) and a Generate action on roles (database/static creds, aws creds, ssh sign and OTP). Secret inputs are write-only: never prefilled and omitted when blank so the stored value is kept. Issued credentials live only in a gcTime-0 mutation and are shown once, with revoke-now for leased credentials. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4fa7ff1497
commit
48746e2150
15 files changed
+1089
-18
No files matched your search
@@ -0,0 +1,97 @@
|
||||
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 config from '../../api/engines/config'
|
||||
import { ENGINES } from '../../api/engines/registry'
|
||||
import { ConfigPanel } from './ConfigPanel'
|
||||
|
||||
vi.mock('../../api/engines/config')
|
||||
|
||||
const client = new BaoClient('http://b', 't')
|
||||
const conn = ENGINES.database.configs[0]
|
||||
|
||||
function renderPanel(type: keyof typeof ENGINES) {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<ConfigPanel client={client} mount={`${type}/`} engine={ENGINES[type]} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return userEvent.setup()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(config.listConfigs).mockResolvedValue(['pg'])
|
||||
})
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
test('creates a database connection, sending the password only when typed', async () => {
|
||||
vi.mocked(config.writeConfig).mockResolvedValue()
|
||||
const user = renderPanel('database')
|
||||
await user.click(await screen.findByRole('button', { name: 'New connection' }))
|
||||
await user.type(screen.getByLabelText('Connection name'), 'main')
|
||||
await user.type(screen.getByLabelText(/^Connection URL/), 'postgresql://u:p@db/app')
|
||||
await user.type(screen.getByLabelText('Admin password'), 's3cret')
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(config.writeConfig).toHaveBeenCalledWith(
|
||||
client,
|
||||
'database/',
|
||||
conn,
|
||||
expect.objectContaining({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://u:p@db/app', password: 's3cret' }),
|
||||
'main',
|
||||
)
|
||||
})
|
||||
|
||||
test('editing keeps the stored password: blank is omitted and nothing is prefilled', async () => {
|
||||
vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao', allowed_roles: ['ro'] })
|
||||
vi.mocked(config.writeConfig).mockResolvedValue()
|
||||
const user = renderPanel('database')
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit pg' }))
|
||||
expect(await screen.findByLabelText('Admin password')).toHaveValue('')
|
||||
expect(screen.getByLabelText('Connection name')).toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
const body = vi.mocked(config.writeConfig).mock.calls[0][3]
|
||||
expect(body).toMatchObject({ connection_url: 'postgresql://x', allowed_roles: ['ro'], username: 'bao' })
|
||||
expect(body).not.toHaveProperty('password')
|
||||
})
|
||||
|
||||
test('rotating root credentials asks first', async () => {
|
||||
vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x' })
|
||||
vi.mocked(config.runAction).mockResolvedValue()
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
|
||||
const user = renderPanel('database')
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit pg' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Rotate root credentials' }))
|
||||
expect(config.runAction).not.toHaveBeenCalled()
|
||||
|
||||
confirm.mockReturnValue(true)
|
||||
await user.click(screen.getByRole('button', { name: 'Rotate root credentials' }))
|
||||
expect(config.runAction).toHaveBeenCalledWith(client, 'database/', conn.actions![0], 'pg')
|
||||
})
|
||||
|
||||
test('aws shows root and lease configs, loaded from their own endpoints', async () => {
|
||||
vi.mocked(config.readConfig).mockImplementation(async (_c, _m, kind) =>
|
||||
kind.id === 'root' ? { access_key: 'AKIA1', region: 'eu-west-1' } : null,
|
||||
)
|
||||
renderPanel('aws')
|
||||
expect(await screen.findByDisplayValue('AKIA1')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Secret key')).toHaveValue('')
|
||||
expect(screen.getByLabelText('Default lease')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('ssh CA: shows the public key and generating asks first', async () => {
|
||||
vi.mocked(config.readConfig).mockResolvedValue({ public_key: 'ssh-rsa AAAAca' })
|
||||
vi.mocked(config.runAction).mockResolvedValue()
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true)
|
||||
const user = renderPanel('ssh')
|
||||
expect(await screen.findByLabelText('Current CA public key')).toHaveValue('ssh-rsa AAAAca')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate signing key' }))
|
||||
expect(config.runAction).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.configs[0].actions![0], undefined)
|
||||
})
|
||||
|
||||
test('shows the load error', async () => {
|
||||
vi.mocked(config.listConfigs).mockRejectedValue(new Error('permission denied'))
|
||||
renderPanel('database')
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from '../../api/engines/config'
|
||||
import type { ConfigKind, EngineDef } from '../../api/engines/registry'
|
||||
import { draftFromRole, emptyDraft, payloadFromDraft, type RoleData, type RoleDraft } from '../../api/engines/roles'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { RoleEditor } from './RoleEditor'
|
||||
|
||||
function ConfigEditor({ client, mount, kind, name, initial, onDone }: {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
kind: ConfigKind
|
||||
/** Config name for named kinds; undefined for single-endpoint configs. */
|
||||
name?: string
|
||||
/** Existing values (null when nothing is configured yet). */
|
||||
initial: RoleData | null
|
||||
onDone: () => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const [draft, setDraft] = useState<RoleDraft>(() =>
|
||||
initial ? draftFromRole(kind, name ?? '', initial) : { ...emptyDraft(kind), name: name ?? '' },
|
||||
)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
const done = () => qc.invalidateQueries({ queryKey: ['engine-config', mount, kind.id] })
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (d: RoleDraft) => writeConfig(client, mount, kind, payloadFromDraft(kind, d), kind.named ? d.name.trim() : undefined),
|
||||
onSuccess: async () => {
|
||||
await done()
|
||||
onDone()
|
||||
},
|
||||
})
|
||||
const act = useMutation({
|
||||
mutationFn: (id: string) => runAction(client, mount, kind.actions!.find((a) => a.id === id)!, name),
|
||||
onSuccess: done,
|
||||
})
|
||||
const remove = useMutation({
|
||||
mutationFn: () => deleteConfig(client, mount, kind, name),
|
||||
onSuccess: async () => {
|
||||
await done()
|
||||
onDone()
|
||||
},
|
||||
})
|
||||
|
||||
const shown = kind.shown?.filter((s) => typeof initial?.[s.key] === 'string' && initial[s.key] !== '')
|
||||
return (
|
||||
<div>
|
||||
{shown?.map((s) => (
|
||||
<label key={s.key}>
|
||||
{s.label}
|
||||
<textarea readOnly rows={3} value={String(initial?.[s.key])} />
|
||||
</label>
|
||||
))}
|
||||
<RoleEditor
|
||||
kind={kind}
|
||||
noun={kind.named ? 'connection' : kind.label.toLowerCase()}
|
||||
showName={kind.named}
|
||||
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={onDone}
|
||||
/>
|
||||
{(initial !== null || !kind.named) &&
|
||||
kind.actions?.map((a) => (
|
||||
<button
|
||||
key={a.id}
|
||||
type="button"
|
||||
disabled={act.isPending}
|
||||
onClick={async () => {
|
||||
if (await confirm(a.confirm)) act.mutate(a.id)
|
||||
}}
|
||||
>
|
||||
{a.label}
|
||||
</button>
|
||||
))}
|
||||
{kind.deletable && initial !== null && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: `Delete ${kind.named ? `“${name}”` : kind.label.toLowerCase()}?`, message: 'This cannot be undone.', confirmLabel: 'Delete' }))
|
||||
remove.mutate()
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
{act.isSuccess && <p role="status">Done.</p>}
|
||||
{act.error && <p role="alert">{act.error.message}</p>}
|
||||
{remove.error && <p role="alert">{remove.error.message}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SingleConfig({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
|
||||
const q = useQuery({ queryKey: ['engine-config', mount, kind.id, ''], queryFn: () => readConfig(client, mount, kind) })
|
||||
if (q.isPending) return <p role="status">Loading…</p>
|
||||
if (q.error) return <p role="alert">{q.error.message}</p>
|
||||
// `key` remounts the form with fresh values after a save or action reloads the config.
|
||||
return (
|
||||
<ConfigEditor
|
||||
key={JSON.stringify(q.data)}
|
||||
client={client}
|
||||
mount={mount}
|
||||
kind={kind}
|
||||
initial={q.data}
|
||||
onDone={() => void q.refetch()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NamedConfigs({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
|
||||
const [editing, setEditing] = useState<{ name?: string; initial: RoleData | null } | null>(null)
|
||||
const names = useQuery({ queryKey: ['engine-config', mount, kind.id], queryFn: () => listConfigs(client, mount, kind) })
|
||||
const open = useMutation({
|
||||
mutationFn: (name: string) => readConfig(client, mount, kind, name),
|
||||
onSuccess: (initial, name) => setEditing({ name, initial }),
|
||||
})
|
||||
return (
|
||||
<div>
|
||||
<ListState query={names} empty={`No ${kind.label.toLowerCase()} yet.`} />
|
||||
{!!names.data?.length && (
|
||||
<table aria-label={kind.label}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{names.data.map((n) => (
|
||||
<tr key={n}>
|
||||
<td>{n}</td>
|
||||
<td>
|
||||
<button type="button" aria-label={`Edit ${n}`} onClick={() => open.mutate(n)}>
|
||||
Edit
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{open.error && <p role="alert">{open.error.message}</p>}
|
||||
{!editing && (
|
||||
<button type="button" onClick={() => setEditing({ initial: null })}>
|
||||
New connection
|
||||
</button>
|
||||
)}
|
||||
{editing && (
|
||||
<ConfigEditor
|
||||
key={editing.name ?? 'new'}
|
||||
client={client}
|
||||
mount={mount}
|
||||
kind={kind}
|
||||
name={editing.name}
|
||||
initial={editing.initial}
|
||||
onDone={() => setEditing(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ConfigPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
|
||||
return (
|
||||
<section aria-label="Config">
|
||||
{engine.configs.map((kind) => (
|
||||
<div key={kind.id}>
|
||||
<h3>{kind.label}</h3>
|
||||
{kind.named ? <NamedConfigs client={client} mount={mount} kind={kind} /> : <SingleConfig client={client} mount={mount} kind={kind} />}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,36 @@
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { engineFor } from '../../api/engines/registry'
|
||||
import type { Mount } from '../../api/secrets'
|
||||
import { ConfigPanel } from './ConfigPanel'
|
||||
import { RolesPanel } from './RolesPanel'
|
||||
|
||||
/** Roles (and, in later phases, Config / Leases) for a dynamic secrets engine. */
|
||||
type Tab = 'roles' | 'config'
|
||||
|
||||
/** Roles and Config (and, in a later phase, Leases) for a dynamic secrets engine. */
|
||||
export function EngineView({ client, mount }: { client: BaoClient; mount: Mount }) {
|
||||
const engine = engineFor(mount.type)
|
||||
const [tab, setTab] = useState<Tab>('roles')
|
||||
const tabs: { id: Tab; label: string }[] = [{ id: 'roles', label: 'Roles' }]
|
||||
if (engine.configs.length > 0) tabs.push({ id: 'config', label: 'Config' })
|
||||
const current = tabs.some((t) => t.id === tab) ? tab : 'roles'
|
||||
|
||||
return (
|
||||
<div className="engine-view">
|
||||
<h2>
|
||||
{engine.label} · {mount.path}
|
||||
</h2>
|
||||
<RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />
|
||||
{tabs.length > 1 && (
|
||||
<div role="tablist" aria-label="Engine" className="tabs">
|
||||
{tabs.map((t) => (
|
||||
<button key={t.id} type="button" role="tab" aria-selected={t.id === current} onClick={() => setTab(t.id)}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{current === 'roles' && <RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
{current === 'config' && <ConfigPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, test, vi } from 'vitest'
|
||||
import { BaoClient } from '../../api/bao'
|
||||
import * as creds from '../../api/engines/creds'
|
||||
import * as leases from '../../api/engines/leases'
|
||||
import { ENGINES } from '../../api/engines/registry'
|
||||
import { GenerateCreds } from './GenerateCreds'
|
||||
|
||||
vi.mock('../../api/engines/creds')
|
||||
vi.mock('../../api/engines/leases')
|
||||
|
||||
const client = new BaoClient('http://b', 't')
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
function setup(type: 'database' | 'ssh', kindIndex = 0) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<GenerateCreds client={client} mount={`${type}/`} role="ro" kinds={ENGINES[type].roleKinds[kindIndex].creds} onClose={onClose} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return { qc, onClose, user: userEvent.setup() }
|
||||
}
|
||||
|
||||
const issued = { leaseId: 'database/creds/ro/abc', leaseDuration: 3600, renewable: true, data: { username: 'v-ro-1', password: 'hunter2' }, warnings: [] }
|
||||
|
||||
test('shows issued credentials once, and keeps them out of every cache', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
|
||||
const { qc, onClose, user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Credentials for ro' })
|
||||
expect(dialog).toHaveTextContent('v-ro-1')
|
||||
expect(dialog).toHaveTextContent('hunter2')
|
||||
expect(dialog).toHaveTextContent('valid for 3600s')
|
||||
expect(JSON.stringify(qc.getQueryCache().getAll().map((q) => q.state.data))).not.toContain('hunter2')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Done' }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(qc.getMutationCache().getAll()).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('revokes the lease on request', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
|
||||
vi.mocked(leases.revokeLease).mockResolvedValue()
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke now' }))
|
||||
expect(leases.revokeLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Lease revoked.')
|
||||
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('credentials without a lease cannot be revoked', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', leaseDuration: 0 })
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByText(/No lease/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('ssh: choose between signing and OTP, and validate inputs before calling OpenBao', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', data: { signed_key: 'ssh-ed25519-cert-v01@openssh.com AAAA' } })
|
||||
const { user } = setup('ssh')
|
||||
// sign is first; the public key is required
|
||||
await user.type(screen.getByLabelText(/^Public key/), ' ')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Public key is required.')
|
||||
expect(creds.generateCreds).not.toHaveBeenCalled()
|
||||
|
||||
await user.selectOptions(screen.getByLabelText('Action'), 'otp')
|
||||
await user.type(screen.getByLabelText('Target IP'), '10.0.0.5')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(creds.generateCreds).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.roleKinds[0].creds[1], 'ro', { ip: '10.0.0.5' })
|
||||
})
|
||||
|
||||
test('shows why generating failed', async () => {
|
||||
vi.mocked(creds.generateCreds).mockRejectedValue(new Error('permission denied'))
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { generateCreds, type Credentials } from '../../api/engines/creds'
|
||||
import { revokeLease } from '../../api/engines/leases'
|
||||
import type { CredKind } from '../../api/engines/registry'
|
||||
import { emptyDraft, payloadFromDraft, type RoleDraft } from '../../api/engines/roles'
|
||||
import { RoleEditor } from './RoleEditor'
|
||||
|
||||
const show = (v: unknown) => (typeof v === 'string' ? v : JSON.stringify(v, null, 2))
|
||||
|
||||
function CopyButton({ text, label }: { text: string; label: string }) {
|
||||
return (
|
||||
<button type="button" aria-label={`Copy ${label}`} onClick={() => void navigator.clipboard?.writeText(text).catch(() => {})}>
|
||||
Copy
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks OpenBao for credentials and shows them exactly once. The result lives only in this component's mutation
|
||||
* (gcTime 0, reset on dismiss): it is never a query, so it is never cached, persisted or put in the URL.
|
||||
*/
|
||||
export function GenerateCreds({
|
||||
client,
|
||||
mount,
|
||||
role,
|
||||
kinds,
|
||||
onClose,
|
||||
}: {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
role: string
|
||||
kinds: CredKind[]
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [kindId, setKindId] = useState(kinds[0].id)
|
||||
const kind = kinds.find((k) => k.id === kindId) ?? kinds[0]
|
||||
const [draft, setDraft] = useState<RoleDraft>(() => emptyDraft({ fields: kind.inputs }))
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
const generate = useMutation({
|
||||
gcTime: 0,
|
||||
mutationFn: (body: Record<string, unknown>) => generateCreds(client, mount, kind, role, body),
|
||||
})
|
||||
const revoke = useMutation({ gcTime: 0, mutationFn: (leaseId: string) => revokeLease(client, leaseId) })
|
||||
|
||||
const close = () => {
|
||||
generate.reset()
|
||||
revoke.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
if (generate.data) return <Issued creds={generate.data} role={role} revoke={revoke} onRevoke={() => revoke.mutate(generate.data.leaseId)} onDone={close} />
|
||||
|
||||
return (
|
||||
<div className="creds">
|
||||
{kinds.length > 1 && (
|
||||
<label>
|
||||
Action
|
||||
<select
|
||||
value={kind.id}
|
||||
onChange={(e) => {
|
||||
const next = kinds.find((k) => k.id === e.target.value) ?? kinds[0]
|
||||
setKindId(next.id)
|
||||
setDraft(emptyDraft({ fields: next.inputs }))
|
||||
setFormError(null)
|
||||
}}
|
||||
>
|
||||
{kinds.map((k) => (
|
||||
<option key={k.id} value={k.id}>
|
||||
{k.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<RoleEditor
|
||||
key={kind.id}
|
||||
kind={{ fields: kind.inputs }}
|
||||
noun={`${kind.label.toLowerCase()} for ${role}`}
|
||||
showName={false}
|
||||
submitLabel="Generate"
|
||||
draft={draft}
|
||||
pending={generate.isPending}
|
||||
error={formError ?? generate.error?.message ?? null}
|
||||
onChange={setDraft}
|
||||
onSubmit={() => {
|
||||
setFormError(null)
|
||||
try {
|
||||
generate.mutate(payloadFromDraft({ fields: kind.inputs }, draft))
|
||||
} catch (e) {
|
||||
setFormError((e as Error).message)
|
||||
}
|
||||
}}
|
||||
onCancel={close}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Issued({
|
||||
creds,
|
||||
role,
|
||||
revoke,
|
||||
onRevoke,
|
||||
onDone,
|
||||
}: {
|
||||
creds: Credentials
|
||||
role: string
|
||||
revoke: { isPending: boolean; isSuccess: boolean; error: Error | null }
|
||||
onRevoke: () => void
|
||||
onDone: () => void
|
||||
}) {
|
||||
return (
|
||||
<section role="dialog" aria-label={`Credentials for ${role}`} className="creds-issued">
|
||||
<h3>Credentials for {role}</h3>
|
||||
<p className="hint">Copy these now. They are not stored and cannot be shown again.</p>
|
||||
<dl>
|
||||
{Object.entries(creds.data).map(([k, v]) => (
|
||||
<div key={k}>
|
||||
<dt>{k}</dt>
|
||||
<dd>
|
||||
<code>{show(v)}</code> <CopyButton text={show(v)} label={k} />
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{creds.leaseId ? (
|
||||
<p>
|
||||
Lease <code>{creds.leaseId}</code>
|
||||
{creds.leaseDuration > 0 && ` · valid for ${creds.leaseDuration}s`}
|
||||
</p>
|
||||
) : (
|
||||
<p className="hint">No lease: these credentials are not revoked when they expire.</p>
|
||||
)}
|
||||
{creds.warnings.map((w) => (
|
||||
<p key={w} className="hint">
|
||||
{w}
|
||||
</p>
|
||||
))}
|
||||
{revoke.error && <p role="alert">{revoke.error.message}</p>}
|
||||
{revoke.isSuccess && <p role="status">Lease revoked.</p>}
|
||||
<div className="form-actions">
|
||||
{creds.leaseId && !revoke.isSuccess && (
|
||||
<button type="button" onClick={onRevoke} disabled={revoke.isPending}>
|
||||
Revoke now
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={onDone}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useId, type FormEvent } from 'react'
|
||||
import type { FieldDef, RoleKind } from '../../api/engines/registry'
|
||||
import type { RoleDraft } from '../../api/engines/roles'
|
||||
import type { FieldDef } from '../../api/engines/registry'
|
||||
import type { RoleDraft, Schema } from '../../api/engines/roles'
|
||||
|
||||
function Field({ field, value, onChange }: { field: FieldDef; value: string | boolean; onChange: (v: string | boolean) => void }) {
|
||||
const helpId = useId()
|
||||
@@ -19,6 +19,36 @@ function Field({ field, value, onChange }: { field: FieldDef; value: string | bo
|
||||
</label>
|
||||
)
|
||||
}
|
||||
if (field.type === 'secret') {
|
||||
const hint = 'Write-only. Leave blank to keep the stored value.'
|
||||
return (
|
||||
<label>
|
||||
{field.label}
|
||||
{field.multiline ? (
|
||||
<textarea
|
||||
value={String(value)}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
rows={4}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={hint}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="password"
|
||||
value={String(value)}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
required={field.required}
|
||||
autoComplete="new-password"
|
||||
placeholder={hint}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
)}
|
||||
{help}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
if (field.type === 'select') {
|
||||
return (
|
||||
<label>
|
||||
@@ -65,6 +95,9 @@ function Field({ field, value, onChange }: { field: FieldDef; value: string | bo
|
||||
|
||||
export function RoleEditor({
|
||||
kind,
|
||||
noun = 'role',
|
||||
showName = true,
|
||||
submitLabel = 'Save',
|
||||
draft,
|
||||
pending,
|
||||
error,
|
||||
@@ -72,7 +105,12 @@ export function RoleEditor({
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: {
|
||||
kind: RoleKind
|
||||
kind: Schema
|
||||
/** What is being edited, for the form title: "role", "connection", ... */
|
||||
noun?: string
|
||||
/** False for single-endpoint configs that have no name. */
|
||||
showName?: boolean
|
||||
submitLabel?: string
|
||||
draft: RoleDraft
|
||||
pending: boolean
|
||||
error: string | null
|
||||
@@ -80,7 +118,7 @@ export function RoleEditor({
|
||||
onSubmit: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const title = draft.isNew ? `New ${kind.label.toLowerCase()} role` : `Edit ${draft.name}`
|
||||
const title = draft.isNew ? `New ${noun}` : showName ? `Edit ${draft.name}` : `Edit ${noun}`
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
onSubmit()
|
||||
@@ -88,10 +126,12 @@ export function RoleEditor({
|
||||
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>
|
||||
{showName && (
|
||||
<label>
|
||||
{noun[0].toUpperCase() + noun.slice(1)} 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)
|
||||
@@ -110,7 +150,7 @@ export function RoleEditor({
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={pending}>
|
||||
Save
|
||||
{submitLabel}
|
||||
</button>
|
||||
<button type="button" onClick={onCancel}>
|
||||
Cancel
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../../api/engines/roles'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { GenerateCreds } from './GenerateCreds'
|
||||
import { RoleEditor } from './RoleEditor'
|
||||
|
||||
export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
|
||||
@@ -23,6 +24,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
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 [credsFor, setCredsFor] = useState<string | null>(null)
|
||||
|
||||
const key = ['engine-roles', mount, kind.id]
|
||||
const roles = useQuery({ queryKey: key, queryFn: () => listRoles(client, mount, kind) })
|
||||
@@ -49,6 +51,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
const switchKind = (id: string) => {
|
||||
setKindId(id)
|
||||
setDraft(null)
|
||||
setCredsFor(null)
|
||||
save.reset()
|
||||
}
|
||||
|
||||
@@ -77,6 +80,11 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
<tr key={name}>
|
||||
<td>{name}</td>
|
||||
<td>
|
||||
{kind.creds.length > 0 && (
|
||||
<button type="button" aria-label={`Generate ${name}`} onClick={() => setCredsFor(name)}>
|
||||
Generate
|
||||
</button>
|
||||
)}
|
||||
<button type="button" aria-label={`Edit ${name}`} onClick={() => edit.mutate(name)}>
|
||||
Edit
|
||||
</button>
|
||||
@@ -102,6 +110,16 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{credsFor && (
|
||||
<GenerateCreds
|
||||
key={`${kind.id}/${credsFor}`}
|
||||
client={client}
|
||||
mount={mount}
|
||||
role={credsFor}
|
||||
kinds={kind.creds}
|
||||
onClose={() => setCredsFor(null)}
|
||||
/>
|
||||
)}
|
||||
{remove.error && <p role="alert">{remove.error.message}</p>}
|
||||
{edit.error && <p role="alert">{edit.error.message}</p>}
|
||||
{!draft && (
|
||||
|
||||
Reference in new issue
Block a user