Add grant/revoke flow with managed per-identity policies
CI / integration (push) Successful in 12s
CI / check (push) Successful in 15s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-20 11:30:35 +01:00
1 parent cd1438987b
commit 5180e1bb74
11 files changed
+720 -1

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } 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 grants from '../../api/grants'
import * as secrets from '../../api/secrets'
import { AccessEditor } from './AccessEditor'
vi.mock('../../api/grants')
vi.mock('../../api/secrets')
const client = new BaoClient('http://b', 't')
const target = { kind: 'user' as const, name: 'alice' }
const state = (over: Partial<grants.GrantState> = {}): grants.GrantState => ({
policyName: 'envbao-user-alice',
hcl: '# envbao-owner: user:alice\npath "secret/data/app/*" {\n capabilities = ["read"]\n}\n',
managed: {
owner: 'user:alice',
editable: true,
reasons: [],
grants: [{ path: 'secret/data/app/*', capabilities: ['read'] }],
},
attached: true,
otherPolicies: ['default'],
...over,
})
beforeEach(() => {
vi.mocked(grants.getGrantState).mockResolvedValue(state())
vi.mocked(secrets.listKvMounts).mockResolvedValue([{ path: 'secret/' }])
vi.mocked(secrets.readPolicyHcl).mockResolvedValue('path "x" { capabilities = ["read"] }')
})
afterEach(() => vi.resetAllMocks())
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<AccessEditor client={client} target={target} onClose={() => {}} />
</QueryClientProvider>,
)
return userEvent.setup()
}
test('shows managed grants and read-only other policies', async () => {
const user = setup()
expect(await screen.findByText('secret/data/app/*')).toBeInTheDocument()
const other = screen.getByText('default').closest('li')!
await user.click(within(other).getByRole('button', { name: 'View' }))
expect(await within(other).findByText(/capabilities/)).toBeInTheDocument()
})
test('grants KV access split into data and metadata rules', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.type(await screen.findByLabelText('Secret path'), 'db/*')
await user.click(screen.getByLabelText('update'))
await user.click(screen.getByLabelText('list'))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, target, [
{ path: 'secret/data/db/*', capabilities: ['read', 'update'] },
{ path: 'secret/metadata/db/*', capabilities: ['list'] },
])
})
test('validates the path and capabilities before calling the API', async () => {
const user = setup()
await user.type(await screen.findByLabelText('Secret path'), '/bad')
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('must not start with "/"')
expect(grants.grantAccess).not.toHaveBeenCalled()
})
test('revoke asks for confirmation', async () => {
vi.mocked(grants.revokeAccess).mockResolvedValue()
const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Revoke' }))
expect(grants.revokeAccess).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Revoke' }))
expect(grants.revokeAccess).toHaveBeenCalledWith(client, target, ['secret/data/app/*'])
confirm.mockRestore()
})
test('a policy edited outside EnvBao is read-only', async () => {
vi.mocked(grants.getGrantState).mockResolvedValue(
state({ managed: { owner: 'user:alice', editable: false, reasons: ['x: Constraint "allowed_parameters"'], grants: [{ path: 'x', capabilities: ['read'] }] } }),
)
setup()
expect(await screen.findByRole('alert')).toHaveTextContent('changed outside EnvBao')
expect(screen.getByRole('button', { name: 'Revoke' })).toBeDisabled()
expect(screen.queryByRole('form', { name: 'Grant access' })).not.toBeInTheDocument()
})
test('shows load errors', async () => {
vi.mocked(grants.getGrantState).mockRejectedValue(new Error('permission denied'))
setup()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+179
View File
@@ -0,0 +1,179 @@
import { useMutation, useQuery, useQueryClient } 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'
interface Props {
client: BaoClient
target: Target
onClose: () => void
}
function PolicyView({ client, name }: { client: BaoClient; name: string }) {
const [open, setOpen] = useState(false)
const hcl = useQuery({ queryKey: ['policy-hcl', name], queryFn: () => readPolicyHcl(client, name), enabled: open })
return (
<li>
{name}{' '}
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)}>
{open ? 'Hide' : 'View'}
</button>
{open && <pre>{hcl.isPending ? 'Loading…' : (hcl.data ?? 'Could not read this policy.')}</pre>}
</li>
)
}
export function AccessEditor({ client, target, onClose }: Props) {
const qc = useQueryClient()
const stateKey = ['grant-state', target.kind, target.name]
const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) })
const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) })
const [mountChoice, setMount] = useState<string | null>(null)
const [secretPath, setSecretPath] = useState('')
const [caps, setCaps] = useState<KvCapability[]>(['read'])
const [showRaw, setShowRaw] = useState(false)
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 grant = useMutation({
mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)),
onSuccess: () => {
setSecretPath('')
return done()
},
})
const revoke = useMutation({ mutationFn: (path: string) => revokeAccess(client, target, [path]), onSuccess: done })
function submit(e: FormEvent) {
e.preventDefault()
const err = validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null)
setFormError(err)
if (!err) grant.mutate()
}
const s = state.data
const editable = !s?.managed || s.managed.editable
return (
<section aria-label={`Access for ${target.name}`} className="access-editor">
<h2>
Access: {target.kind} “{target.name}”
</h2>
<button type="button" onClick={onClose}>
Close
</button>
{state.error && <p role="alert">{state.error.message}</p>}
{s && (
<>
<h3>Granted by EnvBao</h3>
{s.managed && !s.managed.editable && (
<p role="alert">
This policy was changed outside EnvBao and is read-only here: {s.managed.reasons.join('; ')}
</p>
)}
{s.managed?.grants.length ? (
<table>
<thead>
<tr>
<th>Path</th>
<th>Capabilities</th>
<th />
</tr>
</thead>
<tbody>
{s.managed.grants.map((g) => (
<tr key={g.path}>
<td>
<code>{g.path}</code>
</td>
<td>{g.capabilities.join(', ')}</td>
<td>
<button
type="button"
disabled={!editable}
onClick={() => window.confirm(`Revoke ${g.capabilities.join(', ')} on ${g.path}?`) && revoke.mutate(g.path)}
>
Revoke
</button>
</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No access granted through EnvBao yet.</p>
)}
{s.hcl && (
<p>
<button type="button" aria-expanded={showRaw} onClick={() => setShowRaw(!showRaw)}>
{showRaw ? 'Hide' : 'Show'} policy HCL ({s.policyName})
</button>
</p>
)}
{showRaw && <pre>{s.hcl}</pre>}
{revoke.error && <p role="alert">{revoke.error.message}</p>}
{editable && (
<form onSubmit={submit} aria-label="Grant access">
<h3>Grant access</h3>
<label>
Secrets engine
<select value={mount} onChange={(e) => setMount(e.target.value)}>
{mounts.data?.map((m) => (
<option key={m.path}>{m.path}</option>
))}
</select>
</label>
<label>
Secret path
<input value={secretPath} onChange={(e) => setSecretPath(e.target.value)} placeholder="app/db or app/*" />
</label>
<fieldset>
<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>
<p className="hint">
Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.
A trailing * matches everything below.
</p>
{(formError || grant.error) && <p role="alert">{formError ?? grant.error?.message}</p>}
<button type="submit" disabled={grant.isPending || !mount}>
Grant
</button>
</form>
)}
<h3>Other policies (not managed by EnvBao, read-only)</h3>
{s.otherPolicies.length ? (
<ul>
{s.otherPolicies.map((p) => (
<PolicyView key={p} client={client} name={p} />
))}
</ul>
) : (
<p>None.</p>
)}
</>
)}
</section>
)
}
+6
View File
@@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { addAlias, deleteAlias, deleteEntity, listEntities, saveEntity, userpassAccessor, type Entity } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
@@ -15,6 +16,7 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const [accessFor, setAccessFor] = useState<string | null>(null)
const [aliasName, setAliasName] = useState('')
const refresh = () => qc.invalidateQueries({ queryKey: ['entities'] })
@@ -70,6 +72,9 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
<td>{e.aliases.map((a) => a.name).join(', ') || '—'}</td>
<td>{e.policies.join(', ') || '—'}</td>
<td>
<button type="button" onClick={() => setAccessFor(e.name)}>
Access
</button>{' '}
<button type="button" onClick={() => setDraft({ name: e.name, policies: e.policies, isNew: false, entity: e })}>
Edit
</button>{' '}
@@ -133,6 +138,7 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
)}
</form>
)}
{accessFor && <AccessEditor key={accessFor} client={client} target={{ kind: 'entity', name: accessFor }} onClose={() => setAccessFor(null)} />}
</section>
)
}
+6
View File
@@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
@@ -16,6 +17,7 @@ export function GroupsTab({ client }: { client: BaoClient }) {
const groups = useQuery({ queryKey: ['groups'], queryFn: () => listGroups(client) })
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const [accessFor, setAccessFor] = useState<string | null>(null)
const refresh = () => qc.invalidateQueries({ queryKey: ['groups'] })
const nameOf = (id: string) => entities.data?.find((e) => e.id === id)?.name ?? id
@@ -53,6 +55,9 @@ export function GroupsTab({ client }: { client: BaoClient }) {
<td>{g.member_entity_ids.map(nameOf).join(', ') || '—'}</td>
<td>{g.policies.join(', ') || '—'}</td>
<td>
<button type="button" onClick={() => setAccessFor(g.name)}>
Access
</button>{' '}
<button
type="button"
onClick={() => setDraft({ name: g.name, policies: g.policies, members: g.member_entity_ids, isNew: false })}
@@ -107,6 +112,7 @@ export function GroupsTab({ client }: { client: BaoClient }) {
</div>
</form>
)}
{accessFor && <AccessEditor key={accessFor} client={client} target={{ kind: 'group', name: accessFor }} onClose={() => setAccessFor(null)} />}
</section>
)
}
+6
View File
@@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { deleteUser, listUsers, saveUser } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
@@ -18,6 +19,7 @@ export function UsersTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const users = useQuery({ queryKey: ['users'], queryFn: () => listUsers(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const [accessFor, setAccessFor] = useState<string | null>(null)
const save = useMutation({
mutationFn: (d: Draft) => saveUser(client, { name: d.name, password: d.password, policies: d.policies, ttl: d.ttl }),
@@ -53,6 +55,9 @@ export function UsersTab({ client }: { client: BaoClient }) {
<td>{u.name}</td>
<td>{u.policies.join(', ') || '—'}</td>
<td>
<button type="button" onClick={() => setAccessFor(u.name)}>
Access
</button>{' '}
<button type="button" onClick={() => setDraft({ ...u, password: '', ttl: u.ttl ? `${u.ttl}s` : '', isNew: false })}>
Edit
</button>{' '}
@@ -106,6 +111,7 @@ export function UsersTab({ client }: { client: BaoClient }) {
</div>
</form>
)}
{accessFor && <AccessEditor key={accessFor} client={client} target={{ kind: 'user', name: accessFor }} onClose={() => setAccessFor(null)} />}
</section>
)
}