Add Access Graph view with filters, details panel and revoke
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:34:11 +01:00
1 parent 5180e1bb74
commit 265c618884
11 files changed
+731 -54

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { revokeAccess } from '../../api/grants'
import type { AccessGraph, GraphEdge, GraphNode, PolicyInput } from '../../model/graph'
import { parseManagedPolicy, type GrantTarget } from '../../model/managed'
export type Selection = { kind: 'node'; id: string } | { kind: 'edge'; id: string }
interface Props {
client: BaoClient
full: AccessGraph
policies: PolicyInput[]
selection: Selection | null
onRevoked: () => void
}
const nodeById = (g: AccessGraph, id: string) => g.nodes.find((n) => n.id === id)
const label = (n: GraphNode | undefined) => n?.label ?? '?'
function NodeDetails({ node, full, policies }: { node: GraphNode; full: AccessGraph; policies: PolicyInput[] }) {
const out = full.edges.filter((e) => e.source === node.id)
const into = full.edges.filter((e) => e.target === node.id)
const caps = (e: GraphEdge) => (e.capabilities?.length ? ` (${e.capabilities.join(', ')})` : '')
if (node.type === 'identity') {
return (
<>
<h2>{node.label}</h2>
<p>{node.kind}</p>
<h3>Policies</h3>
<ul>{out.map((e) => <li key={e.id}>{label(nodeById(full, e.target))}</li>)}</ul>
</>
)
}
if (node.type === 'policy') {
const hcl = policies.find((p) => p.name === node.label)?.hcl
return (
<>
<h2>{node.label}</h2>
<p>
{node.missing ? 'Attached but does not exist.' : node.managed ? 'Managed by EnvBao.' : 'Not managed by EnvBao (read-only).'}
</p>
{node.warnings.length > 0 && (
<ul>
{node.warnings.map((w) => (
<li key={w}>⚠ {w}</li>
))}
</ul>
)}
<h3>Used by</h3>
<ul>{into.map((e) => <li key={e.id}>{label(nodeById(full, e.source))}</li>)}</ul>
<h3>Grants</h3>
<ul>
{out.map((e) => (
<li key={e.id}>
<code>{label(nodeById(full, e.target))}</code>
{caps(e)}
</li>
))}
</ul>
{hcl && <pre>{hcl}</pre>}
</>
)
}
// path: who reaches it, via which policy
return (
<>
<h2>
<code>{node.label}</code>
</h2>
<h3>Reached through</h3>
<ul>
{into.map((e) => {
const users = full.edges.filter((x) => x.target === e.source).map((x) => label(nodeById(full, x.source)))
return (
<li key={e.id}>
{label(nodeById(full, e.source))}
{caps(e)}: {users.join(', ') || 'no identity'}
</li>
)
})}
</ul>
</>
)
}
function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoClient; edge: GraphEdge; full: AccessGraph } & Pick<Props, 'policies' | 'onRevoked'>) {
const qc = useQueryClient()
const from = nodeById(full, edge.source)
const to = nodeById(full, edge.target)
const isGrant = from?.type === 'policy' && to?.type === 'path'
const hcl = isGrant ? policies.find((p) => p.name === from.label)?.hcl : null
const managed = hcl ? parseManagedPolicy(hcl) : null
const ownerMatch = managed?.owner ? /^(user|entity|group):(.+)$/.exec(managed.owner) : null
const revoke = useMutation({
mutationFn: () => revokeAccess(client, { kind: ownerMatch![1] as GrantTarget, name: ownerMatch![2] }, [to!.label]),
onSuccess: async () => {
await Promise.all(['access-inputs', 'grant-state', 'users', 'entities', 'groups'].map((k) => qc.invalidateQueries({ queryKey: [k] })))
onRevoked()
},
})
return (
<>
<h2>
{label(from)} → {label(to)}
</h2>
{edge.capabilities && <p>Capabilities: {edge.capabilities.join(', ')}</p>}
{edge.warnings?.map((w) => <p key={w}>⚠ {w}</p>)}
{isGrant && (
<>
{managed?.editable && ownerMatch ? (
<button
type="button"
onClick={() =>
window.confirm(`Revoke access to ${to!.label} from ${ownerMatch[1]} "${ownerMatch[2]}"? Other policies are unaffected.`) &&
revoke.mutate()
}
disabled={revoke.isPending}
>
Revoke
</button>
) : (
<p className="hint">This grant is in a policy EnvBao does not manage (or that was edited outside EnvBao), so it can’t be revoked here.</p>
)}
{revoke.error && <p role="alert">{revoke.error.message}</p>}
</>
)}
</>
)
}
export function Details({ client, full, policies, selection, onRevoked }: Props) {
let body = <p className="hint">Click a node or an edge for details.</p>
if (selection?.kind === 'node') {
const node = nodeById(full, selection.id)
if (node) body = <NodeDetails node={node} full={full} policies={policies} />
} else if (selection?.kind === 'edge') {
const edge = full.edges.find((e) => e.id === selection.id)
if (edge) body = <EdgeDetails client={client} edge={edge} full={full} policies={policies} onRevoked={onRevoked} />
}
return (
<aside className="graph-details" aria-label="Details">
{body}
</aside>
)
}
+140
View File
@@ -0,0 +1,140 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao'
import * as grants from '../../api/grants'
import * as ids from '../../api/identities'
import * as secrets from '../../api/secrets'
import { SessionProvider } from '../../api/session'
import { useSession } from '../../api/useSession'
import * as tokens from '../../api/tokens'
import { renderManagedPolicy } from '../../model/managed'
import { GraphPage } from './GraphPage'
// jsdom can't lay out React Flow, so render nodes/edges as plain buttons that fire the same callbacks.
vi.mock('@xyflow/react', () => ({
ReactFlow: (p: {
nodes: { id: string; data: { label: string } }[]
edges: { id: string; label?: string }[]
onNodeClick: (e: unknown, n: { id: string }) => void
onEdgeClick: (e: unknown, ed: { id: string }) => void
}) => (
<div>
{p.nodes.map((n) => (
<button key={n.id} type="button" onClick={(e) => p.onNodeClick(e, n)}>
node {n.data.label}
</button>
))}
{p.edges.map((ed) => (
<button key={ed.id} type="button" onClick={(e) => p.onEdgeClick(e, ed)}>
edge {ed.id}
</button>
))}
</div>
),
Background: () => null,
Controls: () => null,
MarkerType: { ArrowClosed: 'arrowclosed' },
Position: { Left: 'left', Right: 'right' },
}))
vi.mock('../../api/identities')
vi.mock('../../api/tokens')
vi.mock('../../api/grants')
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof secrets>()), readPolicyHcl: vi.fn() }))
const client = new BaoClient('http://b', 't')
const managedHcl = renderManagedPolicy('user', 'alice', [{ path: 'secret/data/app/*', capabilities: ['read'] }])
const handHcl = 'path "secret/data/other" { capabilities = ["read"] }'
function Connected() {
const { connect } = useSession()
return (
<button type="button" onClick={() => connect(client, { accessor: 'me', display_name: 'me', policies: [], ttl: 0, renewable: false })}>
go
</button>
)
}
beforeEach(() => {
vi.mocked(ids.listUsers).mockResolvedValue([
{ name: 'alice', policies: ['envbao-user-alice', 'default'], ttl: 0 },
{ name: 'bob', policies: ['legacy'], ttl: 0 },
])
vi.mocked(ids.listEntities).mockResolvedValue([])
vi.mocked(ids.listGroups).mockResolvedValue([])
vi.mocked(tokens.listTokens).mockResolvedValue([])
vi.mocked(ids.listPolicyNames).mockResolvedValue(['envbao-user-alice', 'default', 'legacy'])
vi.mocked(secrets.readPolicyHcl).mockImplementation(async (_c, n) =>
n === 'envbao-user-alice' ? managedHcl : n === 'legacy' ? handHcl : 'path "auth/token/lookup-self" { capabilities = ["read"] }',
)
})
afterEach(() => vi.resetAllMocks())
async function open() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<SessionProvider>
<MemoryRouter>
<Connected />
<GraphPage />
</MemoryRouter>
</SessionProvider>
</QueryClientProvider>,
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'go' }))
await screen.findByRole('button', { name: 'node alice' })
return user
}
test('renders identities, policies and paths, hiding the default policy', async () => {
await open()
expect(screen.getByRole('button', { name: 'node envbao-user-alice' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'node secret/data/app/*' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'node default' })).not.toBeInTheDocument()
})
test('can show the default policy', async () => {
const user = await open()
await user.click(screen.getByLabelText(/Hide the default policy/))
expect(screen.getByRole('button', { name: 'node default' })).toBeInTheDocument()
})
test('filters by identity and by path', async () => {
const user = await open()
await user.type(screen.getByLabelText('Identity'), 'bob')
expect(screen.queryByRole('button', { name: 'node alice' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'node secret/data/other' })).toBeInTheDocument()
await user.clear(screen.getByLabelText('Identity'))
await user.type(screen.getByLabelText('Path'), 'app')
expect(screen.queryByRole('button', { name: 'node bob' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'node alice' })).toBeInTheDocument()
await user.type(screen.getByLabelText('Path'), 'zzz')
expect(screen.getByText('Nothing matches.')).toBeInTheDocument()
})
test('node details show who reaches a path', async () => {
const user = await open()
await user.click(screen.getByRole('button', { name: 'node secret/data/app/*' }))
const d = screen.getByRole('complementary', { name: 'Details' })
expect(within(d).getByText(/envbao-user-alice \(read\): alice/)).toBeInTheDocument()
})
test('revokes a grant from a managed policy edge', async () => {
vi.mocked(grants.revokeAccess).mockResolvedValue()
const user = await open()
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(true)
await user.click(screen.getByRole('button', { name: 'edge policy:envbao-user-alice->path:secret/data/app/*' }))
await user.click(screen.getByRole('button', { name: 'Revoke' }))
expect(grants.revokeAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'alice' }, ['secret/data/app/*'])
confirm.mockRestore()
})
test('grants in unmanaged policies cannot be revoked', async () => {
const user = await open()
await user.click(screen.getByRole('button', { name: 'edge policy:legacy->path:secret/data/other' }))
expect(screen.queryByRole('button', { name: 'Revoke' })).not.toBeInTheDocument()
expect(screen.getByText(/does not manage/)).toBeInTheDocument()
})
+130 -1
View File
@@ -1,3 +1,132 @@
import {
Background,
Controls,
MarkerType,
Position,
ReactFlow,
type Edge,
type Node,
} from '@xyflow/react'
import '@xyflow/react/dist/style.css'
import { useQueryClient } from '@tanstack/react-query'
import { useMemo, useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { buildAccessGraph, type AccessGraph } from '../../model/graph'
import { filterGraph } from '../../model/graphFilter'
import { layoutColumns } from '../../model/layout'
import { RequireConnection } from '../shared/RequireConnection'
import { useAccessInputs } from '../shared/useAccessInputs'
import { Details, type Selection } from './Details'
function toFlow(graph: AccessGraph, selected: Selection | null): { nodes: Node[]; edges: Edge[] } {
const pos = layoutColumns(graph)
const nodes: Node[] = graph.nodes.map((n) => ({
id: n.id,
position: pos.get(n.id)!,
data: { label: n.label },
className: [
'gnode',
`gnode-${n.type}`,
n.type === 'policy' && n.missing ? 'gnode-missing' : '',
n.type === 'policy' && n.managed ? 'gnode-managed' : '',
selected?.kind === 'node' && selected.id === n.id ? 'gnode-selected' : '',
].join(' '),
sourcePosition: Position.Right,
targetPosition: Position.Left,
}))
const edges: Edge[] = graph.edges.map((e) => ({
id: e.id,
source: e.source,
target: e.target,
label: e.capabilities?.join(', '),
markerEnd: { type: MarkerType.ArrowClosed },
selected: selected?.kind === 'edge' && selected.id === e.id,
}))
return { nodes, edges }
}
function GraphView({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const inputs = useAccessInputs(client)
const [identity, setIdentity] = useState('')
const [path, setPath] = useState('')
const [hideDefault, setHideDefault] = useState(true)
const [selected, setSelected] = useState<Selection | null>(null)
const full = useMemo(
() => (inputs.data ? buildAccessGraph(inputs.data.identities, inputs.data.policies) : null),
[inputs.data],
)
const shown = useMemo(
() => (full ? filterGraph(full, { identity, path, hidePolicies: hideDefault ? ['default'] : [] }) : null),
[full, identity, path, hideDefault],
)
const flow = useMemo(() => (shown ? toFlow(shown, selected) : null), [shown, selected])
if (inputs.isPending) return <p>Loading…</p>
if (inputs.error) return <p role="alert">{inputs.error.message}</p>
if (!full || !shown || !flow) return null
return (
<>
<div className="graph-toolbar">
<label>
Identity
<input value={identity} onChange={(e) => setIdentity(e.target.value)} placeholder="filter identities" />
</label>
<label>
Path
<input value={path} onChange={(e) => setPath(e.target.value)} placeholder="filter paths" />
</label>
<label className="check">
<input type="checkbox" checked={hideDefault} onChange={(e) => setHideDefault(e.target.checked)} /> Hide the default policy
</label>
<button type="button" onClick={() => qc.invalidateQueries({ queryKey: ['access-inputs'] })} disabled={inputs.isFetching}>
{inputs.isFetching ? 'Refreshing…' : 'Refresh'}
</button>
</div>
{inputs.data.notes.map((n) => (
<p key={n} role="alert">
Incomplete: could not read {n}
</p>
))}
<div className="graph-legend" aria-hidden="true">
<span>Identities → Policies → Paths</span>
<span>Identity→policy edges include policies inherited via entities and groups.</span>
</div>
{shown.nodes.length === 0 ? (
<p>Nothing matches.</p>
) : (
<div className="graph-layout">
<div className="graph-canvas" data-testid="graph-canvas">
<ReactFlow
nodes={flow.nodes}
edges={flow.edges}
fitView
nodesDraggable={false}
nodesConnectable={false}
elementsSelectable
colorMode="system"
onNodeClick={(_, n) => setSelected({ kind: 'node', id: n.id })}
onEdgeClick={(_, e) => setSelected({ kind: 'edge', id: e.id })}
onPaneClick={() => setSelected(null)}
>
<Background />
<Controls showInteractive={false} />
</ReactFlow>
</div>
<Details client={client} full={full} policies={inputs.data.policies} selection={selected} onRevoked={() => setSelected(null)} />
</div>
)}
</>
)
}
export function GraphPage() {
return <h1>Access Graph</h1>
return (
<section>
<h1>Access Graph</h1>
<RequireConnection>{(client) => <GraphView client={client} />}</RequireConnection>
</section>
)
}
+3 -36
View File
@@ -1,11 +1,8 @@
import { useQuery } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { listEntities, listGroups, listPolicyNames, listUsers } from '../../api/identities'
import { dataPath, readPolicyHcl } from '../../api/secrets'
import { listTokens } from '../../api/tokens'
import { dataPath } from '../../api/secrets'
import { accessForPath } from '../../model/graph'
import { resolveIdentities } from '../../model/identities'
import { pathMatches } from '../../model/policy'
import { useAccessInputs } from '../shared/useAccessInputs'
interface Props {
client: BaoClient
@@ -14,37 +11,7 @@ interface Props {
}
export function AccessPanel({ client, mount, secret }: Props) {
const data = useQuery({
queryKey: ['access-inputs'],
queryFn: async () => {
// Each source can be forbidden for a limited admin, so a failure degrades to "none" with a note.
const soft = async <T,>(label: string, p: Promise<T>, fallback: T) => {
try {
return { value: await p, note: null }
} catch (e) {
return { value: fallback, note: `${label}: ${e instanceof Error ? e.message : String(e)}` }
}
}
const [users, entities, groups, tokens, names] = await Promise.all([
soft('users', listUsers(client), []),
soft('entities', listEntities(client), []),
soft('groups', listGroups(client), []),
soft('tokens', listTokens(client), []),
listPolicyNames(client),
])
const policies = await Promise.all(names.map(async (name) => ({ name, hcl: await readPolicyHcl(client, name) })))
return {
identities: resolveIdentities({
users: users.value,
entities: entities.value,
groups: groups.value,
tokens: tokens.value,
}),
policies,
notes: [users, entities, groups, tokens].flatMap((r) => (r.note ? [r.note] : [])),
}
},
})
const data = useAccessInputs(client)
if (data.isPending) return <p>Loading access…</p>
if (data.error) return <p role="alert">Could not load access: {data.error.message}</p>
+49
View File
@@ -0,0 +1,49 @@
import { useQuery } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { listEntities, listGroups, listPolicyNames, listUsers } from '../../api/identities'
import { readPolicyHcl } from '../../api/secrets'
import { listTokens } from '../../api/tokens'
import type { Identity, PolicyInput } from '../../model/graph'
import { resolveIdentities } from '../../model/identities'
export interface AccessInputs {
identities: Identity[]
policies: PolicyInput[]
/** Sources a limited admin could not read, so the picture may be incomplete. */
notes: string[]
}
async function soft<T>(label: string, p: Promise<T>, fallback: T) {
try {
return { value: await p, note: null }
} catch (e) {
return { value: fallback, note: `${label}: ${e instanceof Error ? e.message : String(e)}` }
}
}
/** Everything needed to compute who can reach what. Shared by the Access panel and the graph. */
export function useAccessInputs(client: BaoClient) {
return useQuery({
queryKey: ['access-inputs'],
queryFn: async (): Promise<AccessInputs> => {
const [users, entities, groups, tokens, names] = await Promise.all([
soft('users', listUsers(client), []),
soft('entities', listEntities(client), []),
soft('groups', listGroups(client), []),
soft('tokens', listTokens(client), []),
listPolicyNames(client),
])
const policies = await Promise.all(names.map(async (name) => ({ name, hcl: await readPolicyHcl(client, name) })))
return {
identities: resolveIdentities({
users: users.value,
entities: entities.value,
groups: groups.value,
tokens: tokens.value,
}),
policies,
notes: [users, entities, groups, tokens].flatMap((r) => (r.note ? [r.note] : [])),
}
},
})
}