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

+8 -2
View File
@@ -1,3 +1,4 @@
import type { Capability } from '../../model/policy'
import type { Mount } from '../secrets'
import { isKvV2 } from '../secrets'
@@ -37,6 +38,8 @@ export interface CredKind {
method: 'GET' | 'POST'
/** Request parameters; only sent for POST. */
inputs: FieldDef[]
/** ACL capabilities a token needs on `path` to make this request (and so what "generate" grants). */
capabilities: Capability[]
}
/** A one-off call on a config, e.g. rotating the root credentials. */
@@ -107,7 +110,7 @@ const DATABASE_ROLE: RoleKind = {
{ key: 'default_ttl', label: 'Default TTL', type: 'ttl' },
{ key: 'max_ttl', label: 'Max TTL', type: 'ttl' },
],
creds: [{ id: 'creds', label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [] }],
creds: [{ id: 'creds', label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] }],
}
const DATABASE_STATIC_ROLE: RoleKind = {
@@ -121,7 +124,7 @@ const DATABASE_STATIC_ROLE: RoleKind = {
{ key: 'rotation_period', label: 'Rotation period', type: 'ttl' },
],
creds: [
{ id: 'static-creds', label: 'Read current credentials', path: (r) => `static-creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [] },
{ id: 'static-creds', label: 'Read current credentials', path: (r) => `static-creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] },
],
}
@@ -152,6 +155,7 @@ const AWS_ROLE: RoleKind = {
label: 'Generate credentials',
path: (r) => `creds/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['read', 'update'],
inputs: [
{ key: 'ttl', label: 'TTL', type: 'ttl', help: 'For STS credentials.' },
{ key: 'role_arn', label: 'Role ARN', type: 'text', help: 'Only when the role allows several.' },
@@ -181,6 +185,7 @@ const SSH_ROLE: RoleKind = {
label: 'Sign a public key (CA)',
path: (r) => `sign/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['update'],
inputs: [
{ key: 'public_key', label: 'Public key', type: 'textarea', required: true },
{ key: 'valid_principals', label: 'Valid principals', type: 'text', help: 'Comma separated.' },
@@ -193,6 +198,7 @@ const SSH_ROLE: RoleKind = {
label: 'Generate an OTP',
path: (r) => `creds/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['update'],
inputs: [
{ key: 'ip', label: 'Target IP', type: 'text', required: true },
{ key: 'username', label: 'Username', type: 'text' },
+50 -1
View File
@@ -3,7 +3,11 @@ import { BaoClient } from '../bao'
import { readConfig, runAction, writeConfig, deleteConfig } from './config'
import { generateCreds } from './creds'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases'
import { listMounts } from '../secrets'
import { accessForPath } from '../../model/graph'
import { dynamicGrantRules, renderManagedPolicy } from '../../model/managed'
import { pathMatches } from '../../model/policy'
import { capabilitiesSelf, listMounts } from '../secrets'
import { createToken, revokeToken } from '../tokens'
import { ENGINES } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
@@ -126,3 +130,48 @@ describe('dynamic engine config and credentials', () => {
expect(await readConfig(client, awsMount, lease)).toMatchObject({ lease: '30m0s', lease_max: '2h0m0s' })
})
})
describe('grants on dynamic roles match what OpenBao enforces', () => {
const polName = `it-dyn-${sfx}`
const ca = ENGINES.ssh.configs[0]
let token: Awaited<ReturnType<typeof createToken>>
beforeAll(async () => {
const role = emptyDraft(kind)
role.values.allow_user_certificates = true
role.values.allowed_users = '*'
role.values.default_user = 'alice'
for (const name of ['granted', 'other']) await writeRole(client, mount, kind, name, payloadFromDraft(kind, role))
await runAction(client, mount, ca.actions![0])
const grants = dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length)
await client.request('PUT', `sys/policies/acl/${polName}`, { policy: renderManagedPolicy('user', 'x', grants) })
token = await createToken(client, { displayName: polName, policies: [polName], renewable: false, orphan: false })
})
afterAll(async () => {
await revokeToken(client, token.accessor).catch(() => {})
await client.request('DELETE', `sys/policies/acl/${polName}`).catch(() => {})
})
test('capabilities-self agrees with the access model for granted and other roles', async () => {
const as = client.withToken(token.token)
const hcl = renderManagedPolicy('user', 'x', dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length))
const who = [{ kind: 'user' as const, name: 'x', policies: [polName] }]
for (const role of ['granted', 'other']) {
for (const path of [`${mount}sign/${role}`, `${mount}creds/${role}`, `${mount}roles/${role}`]) {
const real = (await capabilitiesSelf(as, path)).filter((c) => c !== 'deny').sort()
const modelled = accessForPath(who, [{ name: polName, hcl }], path, pathMatches).flatMap((e) => e.capabilities).sort()
expect(modelled, path).toEqual(real)
}
}
})
test('the granted token can sign with its role and not with another', async () => {
const as = client.withToken(token.token)
const out = await generateCreds(as, mount, kind.creds[0], 'granted', { public_key: PUBLIC_KEY })
expect(String(out.data.signed_key)).toContain('cert-v01')
await expect(generateCreds(as, mount, kind.creds[0], 'other', { public_key: PUBLIC_KEY })).rejects.toThrow()
expect(await listRoles(as, mount, kind)).toEqual(expect.arrayContaining(['granted']))
})
})
+38 -2
View File
@@ -4,11 +4,18 @@ 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 roles from '../../api/engines/roles'
import * as secrets from '../../api/secrets'
import { AccessEditor } from './AccessEditor'
vi.mock('../../api/grants')
vi.mock('../../api/secrets')
vi.mock('../../api/engines/roles')
vi.mock('../../api/secrets', async (orig) => ({
...(await orig<typeof secrets>()),
listMounts: vi.fn(),
listSecrets: vi.fn(),
readPolicyHcl: vi.fn(),
}))
const client = new BaoClient('http://b', 't')
const target = { kind: 'user' as const, name: 'alice' }
@@ -29,7 +36,7 @@ const state = (over: Partial<grants.GrantState> = {}): grants.GrantState => ({
beforeEach(() => {
vi.mocked(grants.getGrantState).mockResolvedValue(state())
vi.mocked(secrets.listKvMounts).mockResolvedValue([{ path: 'secret/' }])
vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }])
vi.mocked(secrets.listSecrets).mockImplementation(async (_c, _m, prefix) =>
prefix === ''
? [
@@ -140,3 +147,32 @@ test('shows load errors', async () => {
setup()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
test('grants generate on a dynamic-engine role from the identity side', async () => {
vi.mocked(secrets.listMounts).mockResolvedValue([
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'database/', type: 'database' },
])
vi.mocked(roles.listRoles).mockResolvedValue(['readonly', 'readwrite'])
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.selectOptions(await screen.findByLabelText('Secrets engine'), 'database/')
await user.click(await screen.findByLabelText('readwrite'))
await user.click(screen.getByLabelText(/Manage role/))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, target, [
{ path: 'database/creds/readwrite', capabilities: ['read'] },
{ path: 'database/roles/readwrite', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('a dynamic grant needs a role chosen', async () => {
vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'database/', type: 'database' }])
vi.mocked(roles.listRoles).mockResolvedValue(['readonly'])
const user = setup()
await screen.findByLabelText('readonly')
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Choose a role.')
expect(grants.grantAccess).not.toHaveBeenCalled()
})
+28 -9
View File
@@ -2,13 +2,17 @@ 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 { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
import { engineFor, mountKind } from '../../api/engines/registry'
import { readPolicyHcl } from '../../api/secrets'
import { dynamicGrantRules, kvGrantRules, validateGrantPath, type DynamicAccess, type KvCapability } from '../../model/managed'
import { groupGrants } from '../../model/grantRows'
import { CapabilityChips } from '../shared/CapabilityChips'
import { CapabilityPicker } from '../shared/CapabilityPicker'
import { DynamicAccessPicker } from '../shared/DynamicAccessPicker'
import { useMounts } from '../shared/useMounts'
import { useRefreshAccess } from '../shared/useRefreshAccess'
import { PathPicker } from './PathPicker'
import { RolePicker, type RoleSelection } from './RolePicker'
import { useConfirm } from '../shared/useConfirm'
interface Props {
@@ -35,21 +39,29 @@ export function AccessEditor({ client, target, onClose }: Props) {
const confirm = useConfirm()
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 mounts = useMounts(client)
const [mountChoice, setMount] = useState<string | null>(null)
const [secretPath, setSecretPath] = useState('')
const [caps, setCaps] = useState<KvCapability[]>(['read'])
const [roleSel, setRoleSel] = useState<RoleSelection>({ kindId: '', role: '' })
const [access, setAccess] = useState<DynamicAccess[]>(['generate'])
const [showRaw, setShowRaw] = useState(false)
const [formError, setFormError] = useState<string | null>(null)
const mount = mountChoice ?? mounts.data?.[0]?.path ?? ''
const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0]
const mount = current?.path ?? ''
const dynamic = current !== undefined && mountKind(current) === 'dynamic'
const engine = dynamic ? engineFor(current.type) : null
const roleKind = engine ? (engine.roleKinds.find((k) => k.id === roleSel.kindId) ?? engine.roleKinds[0]) : null
const done = useRefreshAccess()
const grant = useMutation({
mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)),
mutationFn: () =>
grantAccess(client, target, roleKind ? dynamicGrantRules(roleKind, mount, roleSel.role, access) : kvGrantRules(mount, secretPath, caps)),
onSuccess: () => {
setSecretPath('')
setRoleSel({ kindId: roleSel.kindId, role: '' })
return done()
},
})
@@ -57,7 +69,10 @@ export function AccessEditor({ client, target, onClose }: Props) {
function submit(e: FormEvent) {
e.preventDefault()
const err = validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null)
const err = roleKind
? (roleSel.role ? validateGrantPath(`${mount}${roleKind.path}/${roleSel.role}`) : 'Choose a role.') ??
(access.length === 0 ? 'Select at least one kind of access.' : null)
: (validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null))
setFormError(err)
if (!err) grant.mutate()
}
@@ -163,6 +178,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
onChange={(e) => {
setMount(e.target.value)
setSecretPath('')
setRoleSel({ kindId: '', role: '' })
}}
>
{mounts.data?.map((m) => (
@@ -170,10 +186,13 @@ export function AccessEditor({ client, target, onClose }: Props) {
))}
</select>
</label>
{mount && <PathPicker key={mount} client={client} mount={mount} value={secretPath} onChange={setSecretPath} />}
<CapabilityPicker value={caps} onChange={setCaps} />
{mount && engine && <RolePicker key={mount} client={client} mount={mount} engine={engine} value={roleSel} onChange={setRoleSel} />}
{mount && !engine && <PathPicker key={mount} client={client} mount={mount} value={secretPath} onChange={setSecretPath} />}
{engine ? <DynamicAccessPicker value={access} onChange={setAccess} /> : <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.
{engine
? 'Granting a role that already has a grant replaces its access. Unticked access is removed.'
: 'Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.'}
</p>
{(formError || grant.error) && <p role="alert">{formError ?? grant.error?.message}</p>}
<button type="submit" disabled={grant.isPending || !mount}>
+80
View File
@@ -0,0 +1,80 @@
import { useQuery } from '@tanstack/react-query'
import { useId } from 'react'
import type { BaoClient } from '../../api/bao'
import type { EngineDef } from '../../api/engines/registry'
import { listRoles } from '../../api/engines/roles'
export interface RoleSelection {
kindId: string
/** A role name, "*" for every role of the kind, or "" for none chosen yet. */
role: string
}
/** Pick a role of a dynamic engine (or all of them) to grant access to. Lists role names only. */
export function RolePicker({
client,
mount,
engine,
value,
onChange,
}: {
client: BaoClient
mount: string
engine: EngineDef
value: RoleSelection
onChange: (v: RoleSelection) => void
}) {
const id = useId()
const kind = engine.roleKinds.find((k) => k.id === value.kindId) ?? engine.roleKinds[0]
const roles = useQuery({ queryKey: ['engine-roles', mount, kind.id], queryFn: () => listRoles(client, mount, kind) })
const all = value.role === '*'
return (
<fieldset className="path-picker">
<legend>Role</legend>
{engine.roleKinds.length > 1 && (
<label>
Role type
<select value={kind.id} onChange={(e) => onChange({ kindId: e.target.value, role: '' })}>
{engine.roleKinds.map((k) => (
<option key={k.id} value={k.id}>
{k.label}
</option>
))}
</select>
</label>
)}
{roles.isPending && <p className="hint">Loading…</p>}
{roles.error && <p role="alert">Can’t list roles here: {roles.error.message}</p>}
{roles.data?.length === 0 && <p className="hint">No roles in {mount}{kind.path} yet.</p>}
{!!roles.data?.length && (
<ul className="entries" aria-label={`Roles in ${mount}`}>
{roles.data.map((name) => (
<li key={name}>
<label className="entry-secret">
<input
type="radio"
name={`${id}-role`}
checked={value.role === name}
disabled={all}
onChange={() => onChange({ kindId: kind.id, role: name })}
/>
{name}
</label>
</li>
))}
</ul>
)}
<label className="check">
<input
type="checkbox"
checked={all}
onChange={(e) => onChange({ kindId: kind.id, role: e.target.checked ? '*' : '' })}
/>
<span>
Every role in <code>{mount}{kind.path}</code>, including ones added later
</span>
</label>
</fieldset>
)
}
+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)
@@ -0,0 +1,23 @@
import { DYNAMIC_ACCESS, type DynamicAccess } from '../../model/managed'
/** Checkboxes for what a grant on a dynamic-engine role allows. */
export function DynamicAccessPicker({ value, onChange }: { value: DynamicAccess[]; onChange: (v: DynamicAccess[]) => void }) {
return (
<fieldset className="caps">
<legend>Access</legend>
{DYNAMIC_ACCESS.map((a) => (
<label key={a.id} className="check">
<input
type="checkbox"
checked={value.includes(a.id)}
onChange={(e) => onChange(e.target.checked ? [...value, a.id] : value.filter((x) => x !== a.id))}
/>
<span>
{a.label}
<span className="hint"> {a.help}</span>
</span>
</label>
))}
</fieldset>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { useQuery } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { mountKind } from '../../api/engines/registry'
import { listMounts } from '../../api/secrets'
/** KV v2 and dynamic-engine mounts (system, cubbyhole and identity mounts are left out). */
export function useMounts(client: BaoClient) {
return useQuery({
queryKey: ['mounts'],
queryFn: async () => (await listMounts(client)).filter((m) => mountKind(m) !== null),
})
}
+61
View File
@@ -0,0 +1,61 @@
import { expect, test } from 'vitest'
import { ENGINES } from '../api/engines/registry'
import { accessForPath } from './graph'
import { dynamicGrantRules, parseManagedPolicy, renderManagedPolicy } from './managed'
import { pathMatches } from './policy'
const dbRoles = ENGINES.database.roleKinds[0]
const dbStatic = ENGINES.database.roleKinds[1]
const aws = ENGINES.aws.roleKinds[0]
const ssh = ENGINES.ssh.roleKinds[0]
test('database: generate is read on creds, and is removed when not granted', () => {
expect(dynamicGrantRules(dbRoles, 'database/', 'ro', ['generate'])).toEqual([
{ path: 'database/creds/ro', capabilities: ['read'] },
{ path: 'database/roles/ro', capabilities: [] },
])
expect(dynamicGrantRules(dbStatic, 'database/', 'svc', ['generate'])[0]).toEqual({ path: 'database/static-creds/svc', capabilities: ['read'] })
})
test('manage grants role CRUD plus listing, and generate is revoked when unticked', () => {
expect(dynamicGrantRules(dbRoles, 'database', 'ro', ['manage'])).toEqual([
{ path: 'database/creds/ro', capabilities: [] },
{ path: 'database/roles/ro', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('aws and ssh use the capabilities their requests need', () => {
expect(dynamicGrantRules(aws, 'aws/', 'ci', ['generate'])[0]).toEqual({ path: 'aws/creds/ci', capabilities: ['read', 'update'] })
const s = dynamicGrantRules(ssh, 'ssh/', 'ops', ['generate'])
expect(s.slice(0, 2)).toEqual([
{ path: 'ssh/sign/ops', capabilities: ['update'] },
{ path: 'ssh/creds/ops', capabilities: ['update'] },
])
})
test('"*" grants every role of the kind', () => {
expect(dynamicGrantRules(dbRoles, 'database/', '*', ['generate', 'manage'])).toEqual([
{ path: 'database/creds/*', capabilities: ['read'] },
{ path: 'database/roles/*', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('rules survive a managed-policy round trip and resolve in the access model', () => {
const grants = dynamicGrantRules(dbRoles, 'database/', 'ro', ['generate']).filter((g) => g.capabilities.length)
const hcl = renderManagedPolicy('user', 'alice', grants)
const parsed = parseManagedPolicy(hcl)
expect(parsed.editable).toBe(true)
expect(parsed.grants).toEqual(grants)
const entries = accessForPath(
[{ kind: 'user', name: 'alice', policies: ['envbao-user-alice'] }],
[{ name: 'envbao-user-alice', hcl }],
'database/creds/ro',
pathMatches,
)
expect(entries).toHaveLength(1)
expect(entries[0].capabilities).toEqual(['read'])
expect(accessForPath([{ kind: 'user', name: 'alice', policies: ['envbao-user-alice'] }], [{ name: 'envbao-user-alice', hcl }], 'database/creds/other', pathMatches)).toEqual([])
})
+26
View File
@@ -1,3 +1,4 @@
import type { RoleKind } from '../api/engines/registry'
import { MANAGED_PREFIX } from './graph'
import { CAPABILITIES, parsePolicy, type Capability } from './policy'
@@ -94,3 +95,28 @@ export function kvGrantRules(mount: string, secretPath: string, caps: KvCapabili
{ path: `${m}metadata/${secretPath}`, capabilities: caps.includes('list') ? ['list'] : [] },
]
}
/** What a grant on a dynamic-engine role can allow. */
export type DynamicAccess = 'generate' | 'manage'
export const DYNAMIC_ACCESS: { id: DynamicAccess; label: string; help: string }[] = [
{ id: 'generate', label: 'Generate credentials', help: 'Issue database logins, AWS keys, SSH certificates or OTPs from the role.' },
{ id: 'manage', label: 'Manage role', help: 'View, change and delete the role, and list the roles of this kind.' },
]
/**
* Expand a grant on a dynamic-engine role (`role` may be "*" for every role of that kind) into API-path rules.
* Like kvGrantRules, a path that is not granted comes back with no capabilities so that writing the rules removes it;
* the shared "list roles" path is only emitted when managing, so revoking one role never hides the others.
*/
export function dynamicGrantRules(roleKind: RoleKind, mount: string, role: string, access: DynamicAccess[]): Grant[] {
const m = mount.endsWith('/') ? mount : `${mount}/`
const rules: Grant[] = roleKind.creds.map((c) => ({
path: m + c.path(role),
capabilities: access.includes('generate') ? c.capabilities : [],
}))
const manage = access.includes('manage')
rules.push({ path: `${m}${roleKind.path}/${role}`, capabilities: manage ? ['create', 'read', 'update', 'delete'] : [] })
if (manage) rules.push({ path: `${m}${roleKind.path}`, capabilities: ['list'] })
return rules
}