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

+4 -1
View File
@@ -135,6 +135,9 @@ CI runs on Gitea Actions (`.gitea/workflows/`): lint, test, build.
- No server-side audit trail beyond OpenBao's own audit log.
- KV v2 only.
- Only userpass auth, tokens and identity entities/groups are supported.
- Policies not created by the UI (not named `envbao-*`) are shown read-only in the graph.
- Access is granted by writing one managed policy per user, entity or group, named `envbao-<kind>-<name>` (for example `envbao-user-alice`). A managed policy that is edited outside EnvBao becomes read-only in the UI. Other policies are always shown read-only.
- Tokens cannot be granted access after creation (OpenBao fixes a token's policies when it is created), so choose their policies when creating them.
- Grants are KV v2 only: they write `<mount>/data/...` rules for read/create/update/delete and `<mount>/metadata/...` for list.
- The access model follows OpenBao's "most specific path wins" rule, so a broader rule never adds to or overrides a more specific one.
- Glob and templated policy paths are approximated.
- The graph is not paginated, so large instances may be slow.
+112
View File
@@ -0,0 +1,112 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { kvGrantRules } from '../model/managed'
import { BaoClient } from './bao'
import { getGrantState, grantAccess, revokeAccess, type Target } from './grants'
import * as ids from './identities'
import { capabilitiesSelf } from './secrets'
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const secretPath = `it-grant-${sfx}`
const loginCaps = async (user: string, path: string) => {
const { token } = await client.loginUserpass(user, 'pw-123456')
return (await capabilitiesSelf(client.withToken(token), path)).sort()
}
beforeAll(async () => {
const mounts = await client.request<{ data: Record<string, { type: string }> }>('GET', 'sys/auth')
if (!Object.values(mounts.data).some((m) => m.type === 'userpass')) {
await client.request('POST', 'sys/auth/userpass', { type: 'userpass' })
}
})
describe('grant / revoke against a dev OpenBao', () => {
const user: Target = { kind: 'user', name: `it-gu-${sfx}` }
const dataPath = `secret/data/${secretPath}/app/x`
beforeAll(() => ids.saveUser(client, { name: user.name, password: 'pw-123456', policies: ['default'] }))
afterAll(async () => {
await ids.deleteUser(client, user.name).catch(() => {})
await client.request('DELETE', `sys/policies/acl/envbao-user-${user.name}`).catch(() => {})
})
test('granting gives the user the capability on login, keeping existing policies', async () => {
expect(await loginCaps(user.name, dataPath)).toEqual(['deny'])
await grantAccess(client, user, kvGrantRules('secret/', `${secretPath}/app/*`, ['read', 'update', 'list']))
expect(await loginCaps(user.name, dataPath)).toEqual(['read', 'update'])
expect(await loginCaps(user.name, `secret/metadata/${secretPath}/app/x`)).toEqual(['list'])
expect((await ids.readUser(client, user.name)).policies.sort()).toEqual(['default', `envbao-user-${user.name}`])
})
test('granting the same path again replaces its capabilities', async () => {
await grantAccess(client, user, kvGrantRules('secret/', `${secretPath}/app/*`, ['read']))
expect(await loginCaps(user.name, dataPath)).toEqual(['read'])
// the metadata rule was dropped because list was deselected
expect(await loginCaps(user.name, `secret/metadata/${secretPath}/app/x`)).toEqual(['deny'])
})
test('state reports managed grants and unmanaged policies', async () => {
const s = await getGrantState(client, user)
expect(s).toMatchObject({ attached: true, otherPolicies: ['default'] })
expect(s.managed?.editable).toBe(true)
expect(s.managed?.grants).toEqual([{ path: `secret/data/${secretPath}/app/*`, capabilities: ['read'] }])
})
test('revoking the last grant removes access, the policy and the attachment', async () => {
await revokeAccess(client, user, [`secret/data/${secretPath}/app/*`])
expect(await loginCaps(user.name, dataPath)).toEqual(['deny'])
const s = await getGrantState(client, user)
expect(s).toMatchObject({ attached: false, hcl: null, otherPolicies: ['default'] })
})
test('refuses to edit a managed policy that was changed outside EnvBao', async () => {
await grantAccess(client, user, kvGrantRules('secret/', `${secretPath}/a`, ['read']))
await client.request('PUT', `sys/policies/acl/envbao-user-${user.name}`, {
policy: '# envbao-owner: user:' + user.name + '\npath "x" {\n capabilities = ["read"]\n allowed_parameters = { "a" = [] }\n}',
})
await expect(grantAccess(client, user, kvGrantRules('secret/', `${secretPath}/b`, ['read']))).rejects.toThrow(/edited outside/)
})
test('refuses to overwrite a policy owned by a different identity with a colliding name', async () => {
const other: Target = { kind: 'user', name: user.name.toUpperCase() } // same sanitised policy name
await expect(grantAccess(client, other, kvGrantRules('secret/', `${secretPath}/c`, ['read']))).rejects.toThrow(/not managed/)
})
})
describe('entity and group grants', () => {
const uname = `it-eu-${sfx}`
const entity: Target = { kind: 'entity', name: `it-ge-${sfx}` }
const group: Target = { kind: 'group', name: `it-gg-${sfx}` }
const path = `secret/data/${secretPath}/ent`
afterAll(async () => {
await ids.deleteGroup(client, group.name).catch(() => {})
await ids.deleteEntity(client, entity.name).catch(() => {})
await ids.deleteUser(client, uname).catch(() => {})
for (const p of [`envbao-entity-${entity.name}`, `envbao-group-${group.name}`]) {
await client.request('DELETE', `sys/policies/acl/${p}`).catch(() => {})
}
})
test('entity and group policies reach an aliased userpass login', async () => {
await ids.saveUser(client, { name: uname, password: 'pw-123456', policies: ['default'] })
await ids.saveEntity(client, { name: entity.name, policies: [] })
const e = await ids.readEntity(client, entity.name)
await ids.addAlias(client, { name: uname, entityId: e.id, mountAccessor: (await ids.userpassAccessor(client))! })
await ids.saveGroup(client, { name: group.name, policies: [], memberEntityIds: [e.id] })
await grantAccess(client, entity, [{ path, capabilities: ['read'] }])
expect(await loginCaps(uname, path)).toEqual(['read'])
await grantAccess(client, group, [{ path: `${path}2`, capabilities: ['update'] }])
expect(await loginCaps(uname, `${path}2`)).toEqual(['update'])
// group membership is preserved by the policy update
expect((await ids.readGroup(client, group.name)).member_entity_ids).toEqual([e.id])
await revokeAccess(client, entity, [path])
expect(await loginCaps(uname, path)).toEqual(['deny'])
})
})
+104
View File
@@ -0,0 +1,104 @@
import {
managedPolicyName,
ownerTag,
parseManagedPolicy,
removeGrant,
renderManagedPolicy,
upsertGrant,
validateGrantPath,
type Grant,
type GrantTarget,
type ManagedPolicy,
} from '../model/managed'
import type { BaoClient } from './bao'
import { readEntity, readGroup, readUser, saveEntity, saveGroup, saveUser } from './identities'
import { readPolicyHcl } from './secrets'
export interface Target {
kind: GrantTarget
name: string
}
export interface GrantState {
policyName: string
/** Raw HCL of the managed policy, or null if there is none yet. */
hcl: string | null
managed: ManagedPolicy | null
attached: boolean
/** Policies on the identity that EnvBao does not manage (shown read-only). */
otherPolicies: string[]
}
async function attachedPolicies(c: BaoClient, t: Target): Promise<string[]> {
if (t.kind === 'user') return (await readUser(c, t.name)).policies
if (t.kind === 'entity') return (await readEntity(c, t.name)).policies
return (await readGroup(c, t.name)).policies
}
/** Re-read, change and write back the identity's policy list, preserving its other settings. */
async function updateAttached(c: BaoClient, t: Target, change: (p: string[]) => string[]): Promise<void> {
if (t.kind === 'user') {
const u = await readUser(c, t.name)
await saveUser(c, { name: t.name, policies: change(u.policies) })
} else if (t.kind === 'entity') {
const e = await readEntity(c, t.name)
await saveEntity(c, { name: t.name, policies: change(e.policies), disabled: e.disabled })
} else {
const g = await readGroup(c, t.name)
await saveGroup(c, { name: t.name, policies: change(g.policies), memberEntityIds: g.member_entity_ids })
}
}
export async function getGrantState(c: BaoClient, t: Target): Promise<GrantState> {
const policyName = managedPolicyName(t.kind, t.name)
const [hcl, policies] = await Promise.all([readPolicyHcl(c, policyName), attachedPolicies(c, t)])
return {
policyName,
hcl,
managed: hcl === null ? null : parseManagedPolicy(hcl),
attached: policies.includes(policyName),
otherPolicies: policies.filter((p) => p !== policyName),
}
}
async function loadEditable(c: BaoClient, t: Target): Promise<{ policyName: string; grants: Grant[] }> {
const policyName = managedPolicyName(t.kind, t.name)
const hcl = await readPolicyHcl(c, policyName)
if (hcl === null) return { policyName, grants: [] }
const m = parseManagedPolicy(hcl)
// The name is lossy (case/punctuation), so make sure we never clobber another identity's policy.
if (m.owner !== ownerTag(t.kind, t.name)) {
throw new Error(`Policy "${policyName}" exists but is not managed by EnvBao for ${t.kind} "${t.name}".`)
}
if (!m.editable) throw new Error(`Policy "${policyName}" was edited outside EnvBao and cannot be changed here: ${m.reasons.join('; ')}`)
return { policyName, grants: m.grants }
}
async function writePolicy(c: BaoClient, name: string, hcl: string): Promise<void> {
await c.request('PUT', `sys/policies/acl/${encodeURIComponent(name)}`, { policy: hcl })
}
/** Add or replace grants (by path) on the identity's managed policy, and attach it. */
export async function grantAccess(c: BaoClient, t: Target, rules: Grant[]): Promise<void> {
for (const r of rules) {
const err = validateGrantPath(r.path)
if (err) throw new Error(err)
}
const { policyName, grants } = await loadEditable(c, t)
const next = rules.reduce(upsertGrant, grants)
if (next.length === 0) throw new Error('Select at least one capability.')
await writePolicy(c, policyName, renderManagedPolicy(t.kind, t.name, next))
await updateAttached(c, t, (p) => (p.includes(policyName) ? p : [...p, policyName]))
}
/** Remove grants by path. When none remain, the policy is detached and deleted. */
export async function revokeAccess(c: BaoClient, t: Target, paths: string[]): Promise<void> {
const { policyName, grants } = await loadEditable(c, t)
const next = paths.reduce(removeGrant, grants)
if (next.length === 0) {
await updateAttached(c, t, (p) => p.filter((n) => n !== policyName))
await c.request('DELETE', `sys/policies/acl/${encodeURIComponent(policyName)}`)
} else {
await writePolicy(c, policyName, renderManagedPolicy(t.kind, t.name, next))
}
}
+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>
)
}
+12
View File
@@ -103,3 +103,15 @@ label.check {
opacity: 0.7;
font-size: 0.9em;
}
.access-editor {
border-top: 2px solid color-mix(in srgb, currentColor 30%, transparent);
margin-top: 1.5rem;
padding-top: 1rem;
}
pre {
background: color-mix(in srgb, currentColor 8%, transparent);
padding: 0.75rem;
overflow-x: auto;
}
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, test } from 'vitest'
import {
kvGrantRules,
managedPolicyName,
parseManagedPolicy,
removeGrant,
renderManagedPolicy,
upsertGrant,
validateGrantPath,
} from './managed'
import { parsePolicy } from './policy'
describe('managedPolicyName', () => {
test.each([
['user', 'alice', 'envbao-user-alice'],
['group', 'Dev Team', 'envbao-group-dev-team'],
['entity', 'a@b.c', 'envbao-entity-a-b.c'],
] as const)('%s %s', (kind, name, expected) => expect(managedPolicyName(kind, name)).toBe(expected))
})
describe('validateGrantPath', () => {
test.each(['', ' a', '/a', 'a"b', 'a\\b', 'a*/b'])('rejects %j', (p) => expect(validateGrantPath(p)).not.toBeNull())
test.each(['secret/data/app', 'secret/data/app/*', 'secret/data/+/x', 'secret/data/app*'])('accepts %s', (p) =>
expect(validateGrantPath(p)).toBeNull(),
)
})
describe('render / parse round trip', () => {
const grants = [
{ path: 'secret/data/b/*', capabilities: ['update', 'read'] as const },
{ path: 'secret/data/a', capabilities: ['read'] as const },
].map((g) => ({ path: g.path, capabilities: [...g.capabilities] }))
test('rendered policy is valid HCL for the policy parser, sorted, with canonical capability order', () => {
const hcl = renderManagedPolicy('user', 'alice', grants)
expect(parsePolicy(hcl).warnings).toEqual([])
expect(parsePolicy(hcl).rules.map((r) => r.path)).toEqual(['secret/data/a', 'secret/data/b/*'])
expect(hcl).toContain('capabilities = ["read", "update"]')
})
test('parse recovers owner and grants and is editable', () => {
const m = parseManagedPolicy(renderManagedPolicy('group', 'devs', grants))
expect(m.owner).toBe('group:devs')
expect(m.editable).toBe(true)
expect(m.grants.map((g) => g.path)).toEqual(['secret/data/a', 'secret/data/b/*'])
})
test('an empty policy is still valid and editable', () => {
expect(parseManagedPolicy(renderManagedPolicy('user', 'x', [])).editable).toBe(true)
})
test('hand-edited constraints make it non-editable', () => {
const hcl = `# envbao-owner: user:alice\npath "a" {\n capabilities = ["read"]\n allowed_parameters = { "x" = [] }\n}`
const m = parseManagedPolicy(hcl)
expect(m.editable).toBe(false)
expect(m.reasons.join()).toMatch(/allowed_parameters/)
})
test('policies without our marker are not editable', () => {
const m = parseManagedPolicy('path "a" { capabilities = ["read"] }')
expect(m.owner).toBeNull()
expect(m.editable).toBe(false)
})
test('duplicate paths are not editable', () => {
const hcl = `# envbao-owner: user:a\npath "a" { capabilities = ["read"] }\npath "a" { capabilities = ["list"] }`
expect(parseManagedPolicy(hcl).editable).toBe(false)
})
test('unparseable policy is not editable', () => {
expect(parseManagedPolicy('# envbao-owner: user:a\npath "a" {').editable).toBe(false)
})
})
describe('upsertGrant / removeGrant', () => {
const g = [{ path: 'a', capabilities: ['read' as const] }]
test('replaces capabilities for an existing path', () => {
expect(upsertGrant(g, { path: 'a', capabilities: ['update'] })).toEqual([{ path: 'a', capabilities: ['update'] }])
})
test('adds new paths', () => expect(upsertGrant(g, { path: 'b', capabilities: ['read'] })).toHaveLength(2))
test('empty capabilities remove the path', () => expect(upsertGrant(g, { path: 'a', capabilities: [] })).toEqual([]))
test('removeGrant', () => expect(removeGrant(g, 'a')).toEqual([]))
})
describe('kvGrantRules', () => {
test('splits data operations and list into data/ and metadata/ rules', () => {
expect(kvGrantRules('secret/', 'app/*', ['read', 'update', 'list'])).toEqual([
{ path: 'secret/data/app/*', capabilities: ['read', 'update'] },
{ path: 'secret/metadata/app/*', capabilities: ['list'] },
])
})
test('no list means an empty metadata rule (to be dropped by upsert)', () => {
expect(kvGrantRules('secret', 'x', ['read'])[1]).toEqual({ path: 'secret/metadata/x', capabilities: [] })
})
})
+96
View File
@@ -0,0 +1,96 @@
import { MANAGED_PREFIX } from './graph'
import { CAPABILITIES, parsePolicy, type Capability } from './policy'
/** Identity kinds that can hold a managed policy. Tokens cannot: their policies are fixed at creation. */
export type GrantTarget = 'user' | 'entity' | 'group'
export interface Grant {
/** Full API path, e.g. "secret/data/app/*". */
path: string
capabilities: Capability[]
}
export interface ManagedPolicy {
owner: string | null
grants: Grant[]
/** False when the policy has anything the form cannot round-trip (or isn't ours). */
editable: boolean
reasons: string[]
}
const OWNER_RE = /^# envbao-owner: (user|entity|group):(.+)$/m
export const ownerTag = (kind: GrantTarget, name: string) => `${kind}:${name}`
/** OpenBao lowercases policy names; keep to a safe character set. */
export function managedPolicyName(kind: GrantTarget, name: string): string {
const safe = name.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-')
return `${MANAGED_PREFIX}${kind}-${safe}`
}
/** Returns an error message, or null if the path can be written safely into a policy. */
export function validateGrantPath(path: string): string | null {
if (!path.trim()) return 'Path is required.'
if (path !== path.trim()) return 'Path must not start or end with spaces.'
if (path.startsWith('/')) return 'Path must not start with "/".'
if (/["\\\n\r]/.test(path)) return 'Path must not contain quotes, backslashes or line breaks.'
if (path.includes('*') && !path.endsWith('*')) return '"*" is only allowed at the end of a path.'
return null
}
export function renderManagedPolicy(kind: GrantTarget, name: string, grants: Grant[]): string {
const sorted = [...grants].sort((a, b) => a.path.localeCompare(b.path))
const header = [
'# Managed by EnvBao. Changes made outside EnvBao may be overwritten.',
`# envbao-owner: ${ownerTag(kind, name)}`,
]
const blocks = sorted.map((g) => {
const caps = CAPABILITIES.filter((c) => g.capabilities.includes(c))
return `path "${g.path}" {\n capabilities = [${caps.map((c) => `"${c}"`).join(', ')}]\n}`
})
return [...header, '', ...blocks].join('\n') + '\n'
}
export function parseManagedPolicy(hcl: string): ManagedPolicy {
const owner = OWNER_RE.exec(hcl)?.[0].replace('# envbao-owner: ', '') ?? null
const parsed = parsePolicy(hcl)
const reasons: string[] = []
if (!owner) reasons.push('Not created by EnvBao (no owner marker).')
reasons.push(...parsed.warnings)
for (const r of parsed.rules) reasons.push(...r.warnings.map((w) => `${r.path}: ${w}`))
const seen = new Set<string>()
for (const r of parsed.rules) {
if (seen.has(r.path)) reasons.push(`${r.path}: declared more than once`)
seen.add(r.path)
}
return {
owner,
grants: parsed.rules.map((r) => ({ path: r.path, capabilities: r.capabilities })),
editable: reasons.length === 0,
reasons,
}
}
/** Replace the grant for `grant.path`; an empty capability list removes it. */
export function upsertGrant(grants: Grant[], grant: Grant): Grant[] {
const rest = grants.filter((g) => g.path !== grant.path)
return grant.capabilities.length ? [...rest, grant] : rest
}
export const removeGrant = (grants: Grant[], path: string): Grant[] => grants.filter((g) => g.path !== path)
export type KvCapability = 'read' | 'create' | 'update' | 'delete' | 'list'
export const KV_CAPABILITIES: KvCapability[] = ['read', 'create', 'update', 'delete', 'list']
/**
* Expand a KV v2 grant on `mount` + `secretPath` into API-path rules: data operations apply to
* `<mount>data/<path>`, while `list` is a metadata operation on `<mount>metadata/<path>`.
*/
export function kvGrantRules(mount: string, secretPath: string, caps: KvCapability[]): Grant[] {
const m = mount.endsWith('/') ? mount : `${mount}/`
const dataCaps = caps.filter((c): c is Exclude<KvCapability, 'list'> => c !== 'list')
return [
{ path: `${m}data/${secretPath}`, capabilities: dataCaps },
{ path: `${m}metadata/${secretPath}`, capabilities: caps.includes('list') ? ['list'] : [] },
]
}