Secrets: grant access from the secret's detail card (ENB-20)
CI / integration (push) Failing after 12s
CI / check (push) Successful in 16s

Adds a Grant access button to the selected secret. An inline form picks an
identity (user, entity or group), whether to grant just this secret or its
whole folder, and capabilities; the access table refreshes afterwards.

- Extract CapabilityPicker and useRefreshAccess from the Access editor so both
  grant forms share them.
- Stop Enter on the identity and engine dropdowns from submitting the form,
  which could grant access by accident.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-20 13:48:07 +01:00
1 parent 61bb6d912a
commit 791cf9603a
8 files changed
+287 -26

No files matched your search

+7 -22
View File
@@ -1,11 +1,13 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants'
import { listKvMounts, readPolicyHcl } from '../../api/secrets'
import { KV_CAPABILITIES, kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
import { groupGrants } from '../../model/grantRows'
import { CapabilityChips } from '../shared/CapabilityChips'
import { CapabilityPicker } from '../shared/CapabilityPicker'
import { useRefreshAccess } from '../shared/useRefreshAccess'
import { PathPicker } from './PathPicker'
import { useConfirm } from '../shared/useConfirm'
@@ -30,7 +32,6 @@ function PolicyView({ client, name }: { client: BaoClient; name: string }) {
}
export function AccessEditor({ client, target, onClose }: Props) {
const qc = useQueryClient()
const confirm = useConfirm()
const stateKey = ['grant-state', target.kind, target.name]
const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) })
@@ -43,12 +44,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
const [formError, setFormError] = useState<string | null>(null)
const mount = mountChoice ?? mounts.data?.[0]?.path ?? ''
const done = () =>
Promise.all(
[stateKey, ['users'], ['entities'], ['groups'], ['access-inputs'], ['policies']].map((queryKey) =>
qc.invalidateQueries({ queryKey }),
),
)
const done = useRefreshAccess()
const grant = useMutation({
mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)),
@@ -163,6 +159,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
Secrets engine
<select
value={mount}
onKeyDown={(e) => e.key === 'Enter' && e.preventDefault()}
onChange={(e) => {
setMount(e.target.value)
setSecretPath('')
@@ -174,19 +171,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
</select>
</label>
{mount && <PathPicker key={mount} client={client} mount={mount} value={secretPath} onChange={setSecretPath} />}
<fieldset className="caps">
<legend>Capabilities</legend>
{KV_CAPABILITIES.map((c) => (
<label key={c} className="check">
<input
type="checkbox"
checked={caps.includes(c)}
onChange={(e) => setCaps(e.target.checked ? [...caps, c] : caps.filter((x) => x !== c))}
/>{' '}
{c}
</label>
))}
</fieldset>
<CapabilityPicker value={caps} onChange={setCaps} />
<p className="hint">
Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.
</p>
+38 -2
View File
@@ -1,9 +1,11 @@
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { dataPath } from '../../api/secrets'
import { accessForPath } from '../../model/graph'
import { pathMatches } from '../../model/policy'
import { CapabilityChips } from '../shared/CapabilityChips'
import { useAccessInputs } from '../shared/useAccessInputs'
import { GrantHere } from './GrantHere'
interface Props {
client: BaoClient
@@ -14,13 +16,47 @@ interface Props {
export function AccessPanel({ client, mount, secret }: Props) {
const data = useAccessInputs(client)
const path = dataPath(mount, secret)
const [granting, setGranting] = useState(false)
const [granted, setGranted] = useState<string | null>(null)
return (
<section aria-label="Access" className="secret-detail">
<header>
<h2>{secret}</h2>
<code>{path}</code>
<div>
<h2>{secret}</h2>
<code>{path}</code>
</div>
{!granting && (
<button
type="button"
disabled={!data.data}
onClick={() => {
setGranted(null)
setGranting(true)
}}
>
Grant access
</button>
)}
</header>
{granted && (
<p role="status" className="note-ok">
{granted}
</p>
)}
{granting && data.data && (
<GrantHere
client={client}
mount={mount}
secret={secret}
identities={data.data.identities}
onClose={() => setGranting(false)}
onGranted={(message) => {
setGranting(false)
setGranted(message)
}}
/>
)}
{data.isPending && <p className="hint">Loading access…</p>}
{data.error && <p role="alert">Could not load access: {data.error.message}</p>}
{data.data && <Entries data={data.data} path={path} />}
+119
View File
@@ -0,0 +1,119 @@
import { useMutation } from '@tanstack/react-query'
import { useState, type FormEvent, type KeyboardEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { grantAccess } from '../../api/grants'
import type { Identity } from '../../model/graph'
import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
import { CapabilityPicker } from '../shared/CapabilityPicker'
import { useRefreshAccess } from '../shared/useRefreshAccess'
interface Props {
client: BaoClient
mount: string
/** Secret path within the mount, e.g. "app/database". */
secret: string
identities: Identity[]
onClose: () => void
onGranted: (message: string) => void
}
// Enter on a dropdown confirms the choice in some browsers and submits the form in others; never grant by accident.
const noEnterSubmit = (e: KeyboardEvent<HTMLSelectElement>) => e.key === 'Enter' && e.preventDefault()
const GROUPS = [
{ kind: 'user', label: 'Users' },
{ kind: 'entity', label: 'Entities' },
{ kind: 'group', label: 'Groups' },
] as const
/** Grant an identity access to the secret that is open, without leaving the Secrets page. */
export function GrantHere({ client, mount, secret, identities, onClose, onGranted }: Props) {
const refresh = useRefreshAccess()
// Tokens can't hold a managed policy: their policies are fixed when they are created.
const people = GROUPS.flatMap((g) => identities.filter((i) => i.kind === g.kind).sort((a, b) => a.name.localeCompare(b.name)))
const [who, setWho] = useState(0)
const [scope, setScope] = useState<'secret' | 'folder'>('secret')
const [caps, setCaps] = useState<KvCapability[]>(['read'])
const [error, setError] = useState<string | null>(null)
const folder = secret.slice(0, secret.lastIndexOf('/') + 1)
const path = scope === 'secret' ? secret : `${folder}*`
const target = people[who]
const grant = useMutation({
mutationFn: () => grantAccess(client, { kind: target.kind as 'user' | 'entity' | 'group', name: target.name }, kvGrantRules(mount, path, caps)),
onSuccess: async () => {
await refresh()
onGranted(`Granted ${caps.join(', ')} on ${mount}${path} to ${target.kind} “${target.name}”.`)
},
})
function submit(e: FormEvent) {
e.preventDefault()
const err = validateGrantPath(path) ?? (caps.length === 0 ? 'Select at least one capability.' : null)
setError(err)
if (!err) grant.mutate()
}
if (people.length === 0) {
return (
<p className="hint">
There are no users, entities or groups to grant access to yet.{' '}
<button type="button" className="link" onClick={onClose}>
Close
</button>
</p>
)
}
return (
<form onSubmit={submit} aria-label="Grant access to this secret" className="wide grant-here">
<h3>Grant access</h3>
<label>
Who
<select value={who} onChange={(e) => setWho(Number(e.target.value))} onKeyDown={noEnterSubmit}>
{GROUPS.map((g) => {
const items = people.filter((p) => p.kind === g.kind)
return (
items.length > 0 && (
<optgroup key={g.kind} label={g.label}>
{items.map((p) => (
<option key={`${p.kind}:${p.name}`} value={people.indexOf(p)}>
{p.name}
</option>
))}
</optgroup>
)
)
})}
</select>
</label>
<fieldset>
<legend>Where</legend>
<label className="check">
<input type="radio" name="grant-scope" checked={scope === 'secret'} onChange={() => setScope('secret')} />
<span>
Just this secret <code>{mount + secret}</code>
</span>
</label>
<label className="check">
<input type="radio" name="grant-scope" checked={scope === 'folder'} onChange={() => setScope('folder')} />
<span>
Everything in <code>{mount + folder}</code>
<span className="hint"> including subfolders and secrets added later</span>
</span>
</label>
</fieldset>
<CapabilityPicker value={caps} onChange={setCaps} />
{(error || grant.error) && <p role="alert">{error ?? grant.error?.message}</p>}
<div className="form-actions">
<button type="submit" disabled={grant.isPending}>
Grant
</button>
<button type="button" onClick={onClose}>
Cancel
</button>
</div>
</form>
)
}
+55
View File
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao'
import * as grants from '../../api/grants'
import * as ids from '../../api/identities'
import * as api from '../../api/secrets'
import { SessionProvider } from '../../api/session'
@@ -11,6 +12,7 @@ import { useSession } from '../../api/useSession'
import * as tokens from '../../api/tokens'
import { SecretsPage } from './SecretsPage'
vi.mock('../../api/grants')
vi.mock('../../api/identities')
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof api>()), listKvMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() }))
vi.mock('../../api/tokens')
@@ -72,6 +74,59 @@ test('navigates folders and shows who can reach a secret', async () => {
expect(within(panel).getByText('secret/data/app/db')).toBeInTheDocument()
})
async function openSecret() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<SessionProvider>
<MemoryRouter>
<Connected />
<SecretsPage />
</MemoryRouter>
</SessionProvider>
</QueryClientProvider>,
)
const user = userEvent.setup()
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: /db/ }))
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
return user
}
test('grants an identity access to the open secret', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = await openSecret()
await user.selectOptions(screen.getByLabelText('Who'), 'bob')
await user.click(screen.getByLabelText('update'))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'bob' }, [
{ path: 'secret/data/app/db', capabilities: ['read', 'update'] },
{ path: 'secret/metadata/app/db', capabilities: [] },
])
expect(await screen.findByRole('status')).toHaveTextContent('Granted read, update on secret/app/db to user “bob”.')
expect(screen.queryByRole('form', { name: 'Grant access to this secret' })).not.toBeInTheDocument()
})
test('can grant the whole folder instead of just the secret', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = await openSecret()
await user.click(screen.getByLabelText(/Everything in/))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'alice' }, [
{ path: 'secret/data/app/*', capabilities: ['read'] },
{ path: 'secret/metadata/app/*', capabilities: [] },
])
})
test('shows why a grant failed and keeps the form open', async () => {
vi.mocked(grants.grantAccess).mockRejectedValue(new Error('Policy "envbao-user-alice" was edited outside EnvBao'))
const user = await openSecret()
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('edited outside EnvBao')
expect(screen.getByRole('form', { name: 'Grant access to this secret' })).toBeInTheDocument()
})
test('asks to connect first', () => {
render(
<QueryClientProvider client={new QueryClient()}>
+1 -1
View File
@@ -79,7 +79,7 @@ function Browser({ client }: { client: BaoClient }) {
)}
</div>
{selected ? (
<AccessPanel client={client} mount={mount} secret={selected} />
<AccessPanel key={`${mount}${selected}`} client={client} mount={mount} secret={selected} />
) : (
<p className="secret-placeholder">Select a secret to see who can reach it.</p>
)}
+25
View File
@@ -0,0 +1,25 @@
import { KV_CAPABILITIES, type KvCapability } from '../../model/managed'
interface Props {
value: KvCapability[]
onChange: (value: KvCapability[]) => void
}
/** Checkboxes for the KV capabilities a grant can carry. */
export function CapabilityPicker({ value, onChange }: Props) {
return (
<fieldset className="caps">
<legend>Capabilities</legend>
{KV_CAPABILITIES.map((c) => (
<label key={c} className="check">
<input
type="checkbox"
checked={value.includes(c)}
onChange={(e) => onChange(e.target.checked ? [...value, c] : value.filter((x) => x !== c))}
/>{' '}
{c}
</label>
))}
</fieldset>
)
}
+10
View File
@@ -0,0 +1,10 @@
import { useQueryClient } from '@tanstack/react-query'
/** After a grant changes: reload everything that shows who can reach what. */
export function useRefreshAccess() {
const qc = useQueryClient()
return () =>
Promise.all(
['grant-state', 'users', 'entities', 'groups', 'access-inputs', 'policies'].map((k) => qc.invalidateQueries({ queryKey: [k] })),
)
}
+32 -1
View File
@@ -1106,9 +1106,18 @@ button.link:hover:not(:disabled) {
}
.secret-detail header {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
gap: var(--s2) var(--s4);
margin-bottom: var(--s4);
}
.secret-detail header > div {
display: grid;
gap: var(--s1);
margin-bottom: var(--s4);
min-width: 0;
}
.secret-detail h2 {
@@ -1422,3 +1431,25 @@ button.danger-solid:hover:not(:disabled) {
border-color: var(--accent);
color: var(--accent);
}
/* Inline "Grant access" form inside the secret detail card. */
.grant-here {
max-width: none;
margin: 0 0 var(--s4);
background: var(--bg);
}
.caps {
grid-template-columns: repeat(auto-fill, minmax(6rem, 1fr));
}
.caps legend {
grid-column: 1 / -1;
}
.note-ok {
padding: var(--s2) var(--s3);
background: var(--accent-soft);
border-radius: var(--radius);
color: var(--accent);
}