Add Access Graph view with filters, details panel and revoke
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5180e1bb74
commit
265c618884
11 files changed
+731
-54
No files matched your search
Generated
-16
@@ -9,7 +9,6 @@
|
||||
"version": "0.0.0",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@dagrejs/dagre": "^3.1.1",
|
||||
"@tanstack/react-query": "^5.104.5",
|
||||
"@xyflow/react": "^12.12.0",
|
||||
"react": "^19.3.1",
|
||||
@@ -279,21 +278,6 @@
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dagrejs/dagre": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dagrejs/dagre/-/dagre-3.1.1.tgz",
|
||||
"integrity": "sha512-zroZB1dFOFiGgv4Xcrn1DckB1o4aOikPqD2NDQPV0WM//CXGcS6xiD0rNkqHmw6FEg4tabt4nxPLwgCWT+Vb2A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dagrejs/graphlib": "4.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@dagrejs/graphlib": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@dagrejs/graphlib/-/graphlib-4.0.5.tgz",
|
||||
"integrity": "sha512-7xrBTqIts3o+PMUZX97wSc+7TUbW+/rULzGNCTP6yooNVDXbzw4Wutg/H/xOutTB/c/k0YqOAavgPh4/Zk9PFA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@exodus/bytes": {
|
||||
"version": "1.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"test:integration": "vitest run --config vitest.integration.config.ts --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dagrejs/dagre": "^3.1.1",
|
||||
"@tanstack/react-query": "^5.104.5",
|
||||
"@xyflow/react": "^12.12.0",
|
||||
"react": "^19.3.1",
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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] : [])),
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -115,3 +115,72 @@ pre {
|
||||
padding: 0.75rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.graph-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
align-items: end;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.graph-toolbar label {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.graph-legend {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
font-size: 0.85em;
|
||||
opacity: 0.7;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.graph-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 22rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.graph-canvas {
|
||||
height: 70vh;
|
||||
border: 1px solid color-mix(in srgb, currentColor 20%, transparent);
|
||||
}
|
||||
|
||||
.graph-details {
|
||||
overflow: auto;
|
||||
max-height: 70vh;
|
||||
}
|
||||
|
||||
.gnode {
|
||||
width: 300px;
|
||||
font-size: 12px;
|
||||
border-width: 2px;
|
||||
}
|
||||
|
||||
.gnode-identity {
|
||||
border-color: #2d7ff9;
|
||||
}
|
||||
|
||||
.gnode-policy {
|
||||
border-color: #8e44ad;
|
||||
}
|
||||
|
||||
.gnode-managed {
|
||||
border-style: solid;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.gnode-missing {
|
||||
border-style: dashed;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.gnode-path {
|
||||
border-color: #27ae60;
|
||||
}
|
||||
|
||||
.gnode-selected {
|
||||
box-shadow: 0 0 0 3px #d4a017;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { AccessGraph } from './graph'
|
||||
|
||||
export interface GraphFilter {
|
||||
/** Case-insensitive substring of an identity name. */
|
||||
identity: string
|
||||
/** Case-insensitive substring of a path. */
|
||||
path: string
|
||||
/** Policy names to hide (and the paths only they reach). */
|
||||
hidePolicies: string[]
|
||||
}
|
||||
|
||||
export const noFilter: GraphFilter = { identity: '', path: '', hidePolicies: [] }
|
||||
|
||||
const matches = (label: string, q: string) => label.toLowerCase().includes(q.trim().toLowerCase())
|
||||
|
||||
function reach(graph: AccessGraph, seeds: Set<string>, dir: 'down' | 'up'): Set<string> {
|
||||
const seen = new Set(seeds)
|
||||
const queue = [...seeds]
|
||||
while (queue.length) {
|
||||
const id = queue.pop()!
|
||||
for (const e of graph.edges) {
|
||||
const [from, to] = dir === 'down' ? [e.source, e.target] : [e.target, e.source]
|
||||
if (from === id && !seen.has(to)) {
|
||||
seen.add(to)
|
||||
queue.push(to)
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity filter keeps matching identities and everything they reach; path filter keeps matching
|
||||
* paths and everything that reaches them. With both, only what satisfies both remains.
|
||||
*/
|
||||
export function filterGraph(graph: AccessGraph, f: GraphFilter): AccessGraph {
|
||||
let nodes = graph.nodes.filter((n) => !(n.type === 'policy' && f.hidePolicies.includes(n.label)))
|
||||
let edges = graph.edges.filter((e) => nodes.some((n) => n.id === e.source) && nodes.some((n) => n.id === e.target))
|
||||
let g: AccessGraph = { nodes, edges }
|
||||
|
||||
// Hiding a policy can leave paths nothing reaches any more.
|
||||
const reached = new Set(g.edges.map((e) => e.target))
|
||||
g = { ...g, nodes: g.nodes.filter((n) => n.type !== 'path' || reached.has(n.id)) }
|
||||
|
||||
const sets: Set<string>[] = []
|
||||
if (f.identity.trim()) {
|
||||
const seeds = new Set(g.nodes.filter((n) => n.type === 'identity' && matches(n.label, f.identity)).map((n) => n.id))
|
||||
sets.push(reach(g, seeds, 'down'))
|
||||
}
|
||||
if (f.path.trim()) {
|
||||
const seeds = new Set(g.nodes.filter((n) => n.type === 'path' && matches(n.label, f.path)).map((n) => n.id))
|
||||
sets.push(reach(g, seeds, 'up'))
|
||||
}
|
||||
if (sets.length) {
|
||||
const keep = sets.reduce((a, b) => new Set([...a].filter((id) => b.has(id))))
|
||||
nodes = g.nodes.filter((n) => keep.has(n.id))
|
||||
edges = g.edges.filter((e) => keep.has(e.source) && keep.has(e.target))
|
||||
g = { nodes, edges }
|
||||
}
|
||||
return g
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { buildAccessGraph, type Identity } from './graph'
|
||||
import { filterGraph, noFilter } from './graphFilter'
|
||||
import { COLUMN_X, layoutColumns } from './layout'
|
||||
|
||||
const identities: Identity[] = [
|
||||
{ kind: 'user', name: 'alice', policies: ['default', 'app'] },
|
||||
{ kind: 'user', name: 'bob', policies: ['default', 'db'] },
|
||||
{ kind: 'group', name: 'ops', policies: ['db'] },
|
||||
]
|
||||
const policies = [
|
||||
{ name: 'default', hcl: 'path "auth/token/lookup-self" { capabilities = ["read"] }' },
|
||||
{ name: 'app', hcl: 'path "secret/data/app/*" { capabilities = ["read"] }' },
|
||||
{ name: 'db', hcl: 'path "secret/data/db" { capabilities = ["read", "update"] }\npath "secret/data/app/*" { capabilities = ["list"] }' },
|
||||
{ name: 'orphan', hcl: 'path "secret/data/lonely" { capabilities = ["read"] }' },
|
||||
]
|
||||
const graph = buildAccessGraph(identities, policies)
|
||||
const labels = (g: typeof graph, type: string) => g.nodes.filter((n) => n.type === type).map((n) => n.label).sort()
|
||||
|
||||
describe('layoutColumns', () => {
|
||||
const pos = layoutColumns(graph)
|
||||
|
||||
test('places every node in its type column, including unattached policies', () => {
|
||||
for (const n of graph.nodes) expect(pos.get(n.id)!.x).toBe(COLUMN_X[n.type])
|
||||
expect(pos.get('policy:orphan')!.x).toBe(COLUMN_X.policy)
|
||||
})
|
||||
|
||||
test('gives nodes in a column distinct rows', () => {
|
||||
const ys = graph.nodes.filter((n) => n.type === 'policy').map((n) => pos.get(n.id)!.y)
|
||||
expect(new Set(ys).size).toBe(ys.length)
|
||||
})
|
||||
|
||||
test('handles an empty graph', () => expect(layoutColumns({ nodes: [], edges: [] }).size).toBe(0))
|
||||
})
|
||||
|
||||
describe('filterGraph', () => {
|
||||
test('no filter returns everything', () => expect(filterGraph(graph, noFilter)).toEqual(graph))
|
||||
|
||||
test('identity filter keeps what the identity reaches', () => {
|
||||
const g = filterGraph(graph, { ...noFilter, identity: 'ALI' })
|
||||
expect(labels(g, 'identity')).toEqual(['alice'])
|
||||
expect(labels(g, 'policy')).toEqual(['app', 'default'])
|
||||
expect(labels(g, 'path')).toEqual(['auth/token/lookup-self', 'secret/data/app/*'])
|
||||
})
|
||||
|
||||
test('path filter keeps everything that reaches the path', () => {
|
||||
const g = filterGraph(graph, { ...noFilter, path: 'secret/data/db' })
|
||||
expect(labels(g, 'identity')).toEqual(['bob', 'ops'])
|
||||
expect(labels(g, 'policy')).toEqual(['db'])
|
||||
// the policy's other rule is not part of what we asked about only if unreachable; here it is the same policy
|
||||
expect(labels(g, 'path')).toContain('secret/data/db')
|
||||
})
|
||||
|
||||
test('both filters narrow to the intersection', () => {
|
||||
const g = filterGraph(graph, { ...noFilter, identity: 'bob', path: 'app' })
|
||||
expect(labels(g, 'identity')).toEqual(['bob'])
|
||||
expect(labels(g, 'path')).toEqual(['secret/data/app/*'])
|
||||
expect(labels(g, 'policy')).toEqual(['db'])
|
||||
})
|
||||
|
||||
test('no match yields an empty graph', () => {
|
||||
expect(filterGraph(graph, { ...noFilter, identity: 'nobody' }).nodes).toEqual([])
|
||||
})
|
||||
|
||||
test('hiding a policy drops paths only it reached', () => {
|
||||
const g = filterGraph(graph, { ...noFilter, hidePolicies: ['default'] })
|
||||
expect(labels(g, 'policy')).not.toContain('default')
|
||||
expect(labels(g, 'path')).not.toContain('auth/token/lookup-self')
|
||||
expect(g.edges.every((e) => g.nodes.some((n) => n.id === e.source) && g.nodes.some((n) => n.id === e.target))).toBe(true)
|
||||
})
|
||||
|
||||
test('hiding a policy keeps paths other policies still reach', () => {
|
||||
const g = filterGraph(graph, { ...noFilter, hidePolicies: ['app'] })
|
||||
expect(labels(g, 'path')).toContain('secret/data/app/*') // still reached by db
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { AccessGraph, GraphNode } from './graph'
|
||||
|
||||
export const COLUMN_X = { identity: 0, policy: 380, path: 780 } as const
|
||||
export const ROW_HEIGHT = 72
|
||||
|
||||
export interface Position {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict three-column layout (identities | policies | paths). Rows within each column are
|
||||
* ordered by repeated barycenter sweeps to keep edge crossings low.
|
||||
*/
|
||||
export function layoutColumns(graph: AccessGraph): Map<string, Position> {
|
||||
const cols: Record<GraphNode['type'], GraphNode[]> = { identity: [], policy: [], path: [] }
|
||||
for (const n of graph.nodes) cols[n.type].push(n)
|
||||
for (const list of Object.values(cols)) list.sort((a, b) => a.label.localeCompare(b.label))
|
||||
|
||||
const neighbours = new Map<string, string[]>()
|
||||
const link = (a: string, b: string) => neighbours.set(a, [...(neighbours.get(a) ?? []), b])
|
||||
for (const e of graph.edges) {
|
||||
link(e.source, e.target)
|
||||
link(e.target, e.source)
|
||||
}
|
||||
|
||||
const index = new Map<string, number>()
|
||||
const reindex = () => Object.values(cols).forEach((list) => list.forEach((n, i) => index.set(n.id, i)))
|
||||
reindex()
|
||||
|
||||
const sweep = (list: GraphNode[]) => {
|
||||
const key = new Map(
|
||||
list.map((n, i) => {
|
||||
const ns = neighbours.get(n.id) ?? []
|
||||
return [n.id, ns.length ? ns.reduce((sum, id) => sum + (index.get(id) ?? 0), 0) / ns.length : i] as const
|
||||
}),
|
||||
)
|
||||
// stable: ties keep the alphabetical order from before
|
||||
list.sort((a, b) => key.get(a.id)! - key.get(b.id)!)
|
||||
}
|
||||
for (let i = 0; i < 4; i++) {
|
||||
sweep(cols.policy)
|
||||
reindex()
|
||||
sweep(cols.identity)
|
||||
sweep(cols.path)
|
||||
reindex()
|
||||
}
|
||||
|
||||
const pos = new Map<string, Position>()
|
||||
for (const type of ['identity', 'policy', 'path'] as const) {
|
||||
cols[type].forEach((n, i) => pos.set(n.id, { x: COLUMN_X[type], y: i * ROW_HEIGHT }))
|
||||
}
|
||||
return pos
|
||||
}
|
||||
Reference in new issue
Block a user