Add New secret: create KV v2 secrets from the Secrets page
Write-only values, create-only (cas: 0). Admin policy gains secret/data/* create; docs updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d5f5faf2df
commit
c29b0cfd63
12 files changed
+192
-10
No files matched your search
@@ -71,3 +71,13 @@ describe('access model vs sys/capabilities-self', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeSecret', () => {
|
||||
test('creates a secret once and refuses to overwrite it', async () => {
|
||||
const path = `it-${sfx}/new/expo`
|
||||
await secrets.writeSecret(client, 'secret/', path, { TOKEN: 'v1' })
|
||||
await expect(secrets.writeSecret(client, 'secret/', path, { TOKEN: 'v2' })).rejects.toThrow()
|
||||
const res = await client.request<{ data: { data: Record<string, string> } }>('GET', `secret/data/${path}`)
|
||||
expect(res.data.data).toEqual({ TOKEN: 'v1' })
|
||||
})
|
||||
})
|
||||
@@ -72,6 +72,14 @@ export async function listSecrets(c: BaoClient, mount: string, prefix: string):
|
||||
/** API path of a secret's data, which is what ACL policies are written against. */
|
||||
export const dataPath = (mount: string, secret: string) => `${mount}data/${secret}`
|
||||
|
||||
/**
|
||||
* Creates a new KV v2 secret. `cas: 0` makes OpenBao refuse if the secret already exists, so this can never
|
||||
* overwrite a value (and only needs the `create` capability).
|
||||
*/
|
||||
export async function writeSecret(c: BaoClient, mount: string, path: string, data: Record<string, string>): Promise<void> {
|
||||
await c.request('POST', dataPath(mount, enc(path)), { data, options: { cas: 0 } })
|
||||
}
|
||||
|
||||
export async function readPolicyHcl(c: BaoClient, name: string): Promise<string | null> {
|
||||
try {
|
||||
const res = await c.request<{ data: { policy: string } }>('GET', `sys/policies/acl/${encodeURIComponent(name)}`)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { writeSecret } from '../../api/secrets'
|
||||
import { validateSecretPath } from '../../model/mounts'
|
||||
|
||||
interface Row {
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/** Create a new KV v2 secret under the current path. Values are write-only and existing secrets are never overwritten. */
|
||||
export function NewSecretDialog({ client, mount, prefix, onClose, onDone }: {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
prefix: string
|
||||
onClose: () => void
|
||||
onDone: (path: string) => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
const [name, setName] = useState('')
|
||||
const [rows, setRows] = useState<Row[]>([{ key: '', value: '' }])
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: async () => {
|
||||
const path = prefix + name.trim()
|
||||
const data: Record<string, string> = {}
|
||||
for (const r of rows) data[r.key.trim()] = r.value
|
||||
await writeSecret(client, mount, path, data)
|
||||
await qc.invalidateQueries({ queryKey: ['kv-list'] })
|
||||
return path
|
||||
},
|
||||
onSuccess: (path) => onDone(path),
|
||||
})
|
||||
|
||||
const setRow = (i: number, patch: Partial<Row>) => setRows(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)))
|
||||
|
||||
function submit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setFormError(null)
|
||||
const nameError = validateSecretPath(name.trim())
|
||||
if (nameError) return setFormError(nameError)
|
||||
const keys = rows.map((r) => r.key.trim())
|
||||
if (keys.some((k) => !k)) return setFormError('Every key needs a name.')
|
||||
if (new Set(keys).size !== keys.length) return setFormError('Keys must be unique.')
|
||||
create.mutate()
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label="New secret" className="mount-dialog">
|
||||
<form aria-label="New secret form" onSubmit={submit}>
|
||||
<label>
|
||||
Name
|
||||
<span className="hint"> in {mount}{prefix}</span>
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="expo" autoComplete="off" />
|
||||
</label>
|
||||
<div className="kv-rows">
|
||||
{rows.map((r, i) => (
|
||||
<div className="kv-row" key={i}>
|
||||
<input aria-label={`Key ${i + 1}`} placeholder="key" value={r.key} autoComplete="off" onChange={(e) => setRow(i, { key: e.target.value })} />
|
||||
<input aria-label={`Value ${i + 1}`} type="password" placeholder="value" value={r.value} autoComplete="new-password" onChange={(e) => setRow(i, { value: e.target.value })} />
|
||||
<button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((_, j) => j !== i))}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<button type="button" onClick={() => setRows([...rows, { key: '', value: '' }])}>
|
||||
Add key
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="hint">Values are write-only: they are never shown again, and an existing secret is never overwritten.</p>
|
||||
{(formError ?? create.error) && <p role="alert">{formError ?? create.error?.message}</p>}
|
||||
<button type="submit" disabled={create.isPending}>
|
||||
{create.isPending ? 'Saving…' : 'Create'}
|
||||
</button>
|
||||
<button type="button" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import { SecretsPage } from './SecretsPage'
|
||||
|
||||
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/secrets', async (orig) => ({ ...(await orig<typeof api>()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn(), writeSecret: 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(), deleteMount: vi.fn(), mountImpact: vi.fn() }))
|
||||
|
||||
@@ -292,3 +292,28 @@ test('asks to connect first', () => {
|
||||
)
|
||||
expect(screen.getByText(/Not connected/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('adds a new secret under the current folder', async () => {
|
||||
vi.mocked(api.writeSecret).mockResolvedValue()
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<SessionProvider>
|
||||
<MemoryRouter>
|
||||
<Connected />
|
||||
<SecretsPage />
|
||||
</MemoryRouter>
|
||||
</SessionProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'go' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'app/' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'New secret' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }))
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Name is required.')
|
||||
await user.type(screen.getByLabelText(/^Name/), 'expo')
|
||||
await user.type(screen.getByLabelText('Key 1'), 'TOKEN')
|
||||
await user.type(screen.getByLabelText('Value 1'), 's3cret')
|
||||
await user.click(screen.getByRole('button', { name: 'Create' }))
|
||||
expect(api.writeSecret).toHaveBeenCalledWith(client, 'secret/', 'app/expo', { TOKEN: 's3cret' })
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import { AccessPanel } from './AccessPanel'
|
||||
import { DeleteMountDialog } from './DeleteMountDialog'
|
||||
import { EngineView } from './EngineView'
|
||||
import { MountDialog } from './MountDialog'
|
||||
import { NewSecretDialog } from './NewSecretDialog'
|
||||
|
||||
function Browser({ client }: { client: BaoClient }) {
|
||||
const mounts = useMounts(client)
|
||||
@@ -16,7 +17,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' | 'delete' | null>(null)
|
||||
const [dialog, setDialog] = useState<'create' | 'edit' | 'delete' | 'secret' | null>(null)
|
||||
|
||||
const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0] ?? null
|
||||
const mount = current?.path ?? null
|
||||
@@ -58,7 +59,7 @@ function Browser({ client }: { client: BaoClient }) {
|
||||
go('')
|
||||
}}
|
||||
/>
|
||||
) : dialog && dialog !== 'delete' && (
|
||||
) : dialog && dialog !== 'delete' && dialog !== 'secret' && (
|
||||
<MountDialog
|
||||
// Remount per mount so one mount's settings are never shown (or saved) for another.
|
||||
key={dialog === 'edit' ? current?.path : 'create'}
|
||||
@@ -132,12 +133,32 @@ function Browser({ client }: { client: BaoClient }) {
|
||||
Settings
|
||||
</button>
|
||||
)}
|
||||
{isKv && (
|
||||
<button type="button" onClick={() => setDialog(dialog === 'secret' ? null : 'secret')} aria-expanded={dialog === 'secret'}>
|
||||
New secret
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={() => setDialog(dialog === 'delete' ? null : 'delete')} aria-expanded={dialog === 'delete'}>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{dialogs}
|
||||
{dialog === 'secret' && isKv && (
|
||||
<NewSecretDialog
|
||||
key={`${mount}${prefix}`}
|
||||
client={client}
|
||||
mount={mount}
|
||||
prefix={prefix}
|
||||
onClose={closeDialog}
|
||||
onDone={(path) => {
|
||||
closeDialog()
|
||||
const folder = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : ''
|
||||
setPrefix(folder)
|
||||
setSelected(path)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
|
||||
@@ -1573,3 +1573,16 @@ button.danger-solid:hover:not(:disabled) {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
/* New secret form: key/value rows. */
|
||||
.kv-rows {
|
||||
display: grid;
|
||||
gap: var(--s2);
|
||||
margin: var(--s3) 0;
|
||||
}
|
||||
|
||||
.kv-row {
|
||||
display: flex;
|
||||
gap: var(--s2);
|
||||
align-items: center;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'vitest'
|
||||
import { policiesReferencing, validateMountPath } from './mounts'
|
||||
import { policiesReferencing, validateMountPath, validateSecretPath } from './mounts'
|
||||
|
||||
const existing = ['secret/', 'database/', 'team/kv/']
|
||||
|
||||
@@ -38,3 +38,8 @@ test('finds policies with rules under a mount, however the mount is written', ()
|
||||
expect(policiesReferencing(policies, 'secret')).toEqual(['a-uses', 'b-uses'])
|
||||
expect(policiesReferencing(policies, 'nothing/')).toEqual([])
|
||||
})
|
||||
|
||||
test('validateSecretPath accepts plain and nested names and rejects bad ones', () => {
|
||||
for (const p of ['expo', 'shell/expo', 'a b']) expect(validateSecretPath(p), p).toBeNull()
|
||||
for (const p of ['', ' x', '/x', 'x/', 'a//b', 'a/../b', '.']) expect(validateSecretPath(p), p).not.toBeNull()
|
||||
})
|
||||
@@ -42,3 +42,14 @@ export function policiesReferencing(policies: PolicyText[], mount: string): stri
|
||||
.map((p) => p.name)
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
}
|
||||
|
||||
/** Error message for a secret name/path (relative to a KV mount) that can't be used, or null. */
|
||||
export function validateSecretPath(path: string): string | null {
|
||||
if (!path.trim()) return 'Name is required.'
|
||||
if (path !== path.trim()) return 'Name must not start or end with spaces.'
|
||||
if (path.startsWith('/') || path.endsWith('/')) return 'Name must not start or end with "/".'
|
||||
const parts = path.split('/')
|
||||
if (parts.some((p) => !p)) return 'Name must not contain empty parts ("//").'
|
||||
if (parts.some((p) => p === '.' || p === '..')) return 'Name must not contain "." or ".." parts.'
|
||||
return null
|
||||
}
|
||||
Reference in new issue
Block a user