Access: grant and inspect access to dynamic engine roles

dynamicGrantRules expands a grant on a role into the credential paths
its requests need (generate) and the role CRUD paths (manage); unticked
access comes back empty so writing it revokes. Roles get an Access panel
showing who can generate credentials or manage them, and the identity
Access editor can pick dynamic mounts and roles. Checked against
capabilities-self and a real token in the integration tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-11-09 13:51:28 +00:00
1 parent 48ee757e8d
commit 85a318c351
14 files changed
+642 -22

No files matched your search

+14 -3
View File
@@ -64,7 +64,18 @@ export function AccessPanel({ client, mount, secret }: Props) {
)
}
function Entries({ data, path }: { data: NonNullable<ReturnType<typeof useAccessInputs>['data']>; path: string }) {
/** Who can reach `path`, from every identity's effective policies. */
export function Entries({
data,
path,
label = 'Who can access this secret',
empty = 'No identity can reach this secret.',
}: {
data: NonNullable<ReturnType<typeof useAccessInputs>['data']>
path: string
label?: string
empty?: string
}) {
const entries = accessForPath(data.identities, data.policies, path, pathMatches)
return (
<>
@@ -74,9 +85,9 @@ function Entries({ data, path }: { data: NonNullable<ReturnType<typeof useAccess
</p>
))}
{entries.length === 0 ? (
<p>No identity can reach this secret.</p>
<p>{empty}</p>
) : (
<table aria-label="Who can access this secret">
<table aria-label={label}>
<thead>
<tr>
<th>Identity</th>
@@ -0,0 +1,98 @@
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 { ENGINES } from '../../api/engines/registry'
import * as grants from '../../api/grants'
import * as ids from '../../api/identities'
import * as secrets from '../../api/secrets'
import * as tokens from '../../api/tokens'
import { RoleAccessPanel } from './RoleAccessPanel'
vi.mock('../../api/grants')
vi.mock('../../api/identities')
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof secrets>()), readPolicyHcl: vi.fn() }))
vi.mock('../../api/tokens')
const client = new BaoClient('http://b', 't')
const kind = ENGINES.database.roleKinds[0]
beforeEach(() => {
vi.mocked(ids.listUsers).mockResolvedValue([
{ name: 'alice', policies: ['db-ro'], ttl: 0 },
{ name: 'bob', policies: ['other'], ttl: 0 },
])
vi.mocked(ids.listEntities).mockResolvedValue([])
vi.mocked(ids.listGroups).mockResolvedValue([])
vi.mocked(tokens.listTokens).mockResolvedValue([])
vi.mocked(ids.listPolicyNames).mockResolvedValue(['db-ro', 'other'])
vi.mocked(secrets.readPolicyHcl).mockImplementation(async (_c, n) =>
n === 'db-ro' ? 'path "database/creds/*" { capabilities = ["read"] }' : 'path "secret/data/x" { capabilities = ["read"] }',
)
})
afterEach(() => vi.resetAllMocks())
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<RoleAccessPanel client={client} mount="database/" kind={kind} role="ro" onClose={() => {}} />
</QueryClientProvider>,
)
return userEvent.setup()
}
test('shows who can generate credentials from the role', async () => {
setup()
const table = await screen.findByRole('table', { name: 'Who can: Generate credentials' })
const row = within(table).getByText('alice').closest('tr')!
expect(within(row).getByText('db-ro')).toBeInTheDocument()
expect(within(row).getByText('read')).toBeInTheDocument()
expect(within(table).queryByText('bob')).not.toBeInTheDocument()
expect(screen.getByText('No identity can manage this role.')).toBeInTheDocument()
})
test('grants generate on one role', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.selectOptions(screen.getByLabelText('Who'), 'bob')
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'bob' }, [
{ path: 'database/creds/ro', capabilities: ['read'] },
{ path: 'database/roles/ro', capabilities: [] },
])
expect(await screen.findByRole('status')).toHaveTextContent('Granted generate credentials on database/roles/ro to user “bob”.')
})
test('can grant every role, and requires some access', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.click(screen.getByLabelText(/Every role in/))
await user.click(screen.getByLabelText(/Manage role/))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'alice' }, [
{ path: 'database/creds/*', capabilities: ['read'] },
{ path: 'database/roles/*', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('refuses to grant nothing', async () => {
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
const form = screen.getByRole('form', { name: 'Grant access to this role' })
await user.click(within(form).getByLabelText(/Generate credentials/))
await user.click(within(form).getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Select at least one kind of access.')
expect(grants.grantAccess).not.toHaveBeenCalled()
})
test('shows why a grant failed', async () => {
vi.mocked(grants.grantAccess).mockRejectedValue(new Error('Policy was edited outside EnvBao'))
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('edited outside EnvBao')
})
+192
View File
@@ -0,0 +1,192 @@
import { useMutation } from '@tanstack/react-query'
import { useState, type FormEvent, type KeyboardEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import type { RoleKind } from '../../api/engines/registry'
import { grantAccess } from '../../api/grants'
import type { Identity } from '../../model/graph'
import { dynamicGrantRules, validateGrantPath, type DynamicAccess } from '../../model/managed'
import { DynamicAccessPicker } from '../shared/DynamicAccessPicker'
import { useAccessInputs } from '../shared/useAccessInputs'
import { useRefreshAccess } from '../shared/useRefreshAccess'
import { Entries } from './AccessPanel'
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
function GrantRole({ client, mount, kind, role, identities, onClose, onGranted }: {
client: BaoClient
mount: string
kind: RoleKind
role: string
identities: Identity[]
onClose: () => void
onGranted: (message: string) => void
}) {
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 [all, setAll] = useState(false)
const [access, setAccess] = useState<DynamicAccess[]>(['generate'])
const [error, setError] = useState<string | null>(null)
const target = people[who]
const granted = all ? '*' : role
const grant = useMutation({
mutationFn: () =>
grantAccess(client, { kind: target.kind as 'user' | 'entity' | 'group', name: target.name }, dynamicGrantRules(kind, mount, granted, access)),
onSuccess: async () => {
await refresh()
const where = all ? `every role in ${mount}${kind.path}` : `${mount}${kind.path}/${role}`
onGranted(`Granted ${access.map((a) => (a === 'generate' ? 'generate credentials' : 'manage role')).join(' and ')} on ${where} to ${target.kind} “${target.name}”.`)
},
})
function submit(e: FormEvent) {
e.preventDefault()
const err = validateGrantPath(`${mount}${kind.path}/${granted}`) ?? (access.length === 0 ? 'Select at least one kind of access.' : 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 role" 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>
<label className="check">
<input type="checkbox" checked={all} onChange={(e) => setAll(e.target.checked)} />
<span>
Every role in <code>{mount + kind.path}</code>
<span className="hint"> including ones added later</span>
</span>
</label>
<DynamicAccessPicker value={access} onChange={setAccess} />
{(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>
)
}
/** Who can generate credentials from, or manage, one role; and a form to grant that to an identity. */
export function RoleAccessPanel({ client, mount, kind, role, onClose }: {
client: BaoClient
mount: string
kind: RoleKind
role: string
onClose: () => void
}) {
const data = useAccessInputs(client)
const [granting, setGranting] = useState(false)
const [granted, setGranted] = useState<string | null>(null)
const credPaths = kind.creds.map((c) => ({ id: c.id, label: c.label, path: mount + c.path(role) }))
const rolePath = `${mount}${kind.path}/${role}`
return (
<section aria-label={`Access to ${role}`} className="secret-detail">
<header>
<div>
<h2>{role}</h2>
<code>{rolePath}</code>
</div>
<div>
{!granting && (
<button
type="button"
disabled={!data.data}
onClick={() => {
setGranted(null)
setGranting(true)
}}
>
Grant access
</button>
)}
<button type="button" onClick={onClose}>
Close
</button>
</div>
</header>
{granted && (
<p role="status" className="note-ok">
{granted}
</p>
)}
{granting && data.data && (
<GrantRole
client={client}
mount={mount}
kind={kind}
role={role}
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 && (
<>
{data.data.notes.map((n) => (
<p key={n} role="alert">
Incomplete: could not read {n}
</p>
))}
{credPaths.map((c) => (
<div key={c.id}>
<h3>{c.label}</h3>
<code>{c.path}</code>
<Entries data={{ ...data.data, notes: [] }} path={c.path} label={`Who can: ${c.label}`} empty="No identity can do this." />
</div>
))}
<h3>Manage role</h3>
<code>{rolePath}</code>
<Entries data={{ ...data.data, notes: [] }} path={rolePath} label="Who can manage this role" empty="No identity can manage this role." />
</>
)}
</section>
)
}
+9
View File
@@ -15,6 +15,7 @@ import {
import { ListState } from '../shared/ListState'
import { useConfirm } from '../shared/useConfirm'
import { GenerateCreds } from './GenerateCreds'
import { RoleAccessPanel } from './RoleAccessPanel'
import { RoleEditor } from './RoleEditor'
export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
@@ -25,6 +26,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
const [draft, setDraft] = useState<RoleDraft | null>(null)
const [formError, setFormError] = useState<string | null>(null)
const [credsFor, setCredsFor] = useState<string | null>(null)
const [accessFor, setAccessFor] = useState<string | null>(null)
const key = ['engine-roles', mount, kind.id]
const roles = useQuery({ queryKey: key, queryFn: () => listRoles(client, mount, kind) })
@@ -52,6 +54,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
setKindId(id)
setDraft(null)
setCredsFor(null)
setAccessFor(null)
save.reset()
}
@@ -85,6 +88,9 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
Generate
</button>
)}
<button type="button" aria-label={`Access ${name}`} onClick={() => setAccessFor(name)}>
Access
</button>
<button type="button" aria-label={`Edit ${name}`} onClick={() => edit.mutate(name)}>
Edit
</button>
@@ -120,6 +126,9 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
onClose={() => setCredsFor(null)}
/>
)}
{accessFor && (
<RoleAccessPanel key={`${kind.id}/${accessFor}`} client={client} mount={mount} kind={kind} role={accessFor} onClose={() => setAccessFor(null)} />
)}
{remove.error && <p role="alert">{remove.error.message}</p>}
{edit.error && <p role="alert">{edit.error.message}</p>}
{!draft && (
+3 -5
View File
@@ -2,16 +2,14 @@ import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { engineFor, mountKind } from '../../api/engines/registry'
import { listMounts, listSecrets } from '../../api/secrets'
import { listSecrets } from '../../api/secrets'
import { RequireConnection } from '../shared/RequireConnection'
import { useMounts } from '../shared/useMounts'
import { AccessPanel } from './AccessPanel'
import { EngineView } from './EngineView'
function Browser({ client }: { client: BaoClient }) {
const mounts = useQuery({
queryKey: ['mounts'],
queryFn: async () => (await listMounts(client)).filter((m) => mountKind(m) !== null),
})
const mounts = useMounts(client)
const [mountChoice, setMount] = useState<string | null>(null)
const [prefix, setPrefix] = useState('')
const [selected, setSelected] = useState<string | null>(null)