diff --git a/package-lock.json b/package-lock.json
index 1557e61..699f01f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -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",
diff --git a/package.json b/package.json
index 90e1f36..208aabc 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/src/features/graph/Details.tsx b/src/features/graph/Details.tsx
new file mode 100644
index 0000000..1482add
--- /dev/null
+++ b/src/features/graph/Details.tsx
@@ -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 (
+ <>
+
{node.label}
+ {node.kind}
+ Policies
+ {out.map((e) => - {label(nodeById(full, e.target))}
)}
+ >
+ )
+ }
+ if (node.type === 'policy') {
+ const hcl = policies.find((p) => p.name === node.label)?.hcl
+ return (
+ <>
+ {node.label}
+
+ {node.missing ? 'Attached but does not exist.' : node.managed ? 'Managed by EnvBao.' : 'Not managed by EnvBao (read-only).'}
+
+ {node.warnings.length > 0 && (
+
+ {node.warnings.map((w) => (
+ - ⚠ {w}
+ ))}
+
+ )}
+ Used by
+ {into.map((e) => - {label(nodeById(full, e.source))}
)}
+ Grants
+
+ {out.map((e) => (
+ -
+
{label(nodeById(full, e.target))}
+ {caps(e)}
+
+ ))}
+
+ {hcl && {hcl}}
+ >
+ )
+ }
+ // path: who reaches it, via which policy
+ return (
+ <>
+
+ {node.label}
+
+ Reached through
+
+ {into.map((e) => {
+ const users = full.edges.filter((x) => x.target === e.source).map((x) => label(nodeById(full, x.source)))
+ return (
+ -
+ {label(nodeById(full, e.source))}
+ {caps(e)}: {users.join(', ') || 'no identity'}
+
+ )
+ })}
+
+ >
+ )
+}
+
+function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoClient; edge: GraphEdge; full: AccessGraph } & Pick) {
+ 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 (
+ <>
+
+ {label(from)} → {label(to)}
+
+ {edge.capabilities && Capabilities: {edge.capabilities.join(', ')}
}
+ {edge.warnings?.map((w) => ⚠ {w}
)}
+ {isGrant && (
+ <>
+ {managed?.editable && ownerMatch ? (
+
+ ) : (
+ This grant is in a policy EnvBao does not manage (or that was edited outside EnvBao), so it can’t be revoked here.
+ )}
+ {revoke.error && {revoke.error.message}
}
+ >
+ )}
+ >
+ )
+}
+
+export function Details({ client, full, policies, selection, onRevoked }: Props) {
+ let body = Click a node or an edge for details.
+ if (selection?.kind === 'node') {
+ const node = nodeById(full, selection.id)
+ if (node) body =
+ } else if (selection?.kind === 'edge') {
+ const edge = full.edges.find((e) => e.id === selection.id)
+ if (edge) body =
+ }
+ return (
+
+ )
+}
diff --git a/src/features/graph/GraphPage.test.tsx b/src/features/graph/GraphPage.test.tsx
new file mode 100644
index 0000000..8de9572
--- /dev/null
+++ b/src/features/graph/GraphPage.test.tsx
@@ -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
+ }) => (
+
+ {p.nodes.map((n) => (
+
+ ))}
+ {p.edges.map((ed) => (
+
+ ))}
+
+ ),
+ 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()), 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 (
+
+ )
+}
+
+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(
+
+
+
+
+
+
+
+ ,
+ )
+ 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()
+})
diff --git a/src/features/graph/GraphPage.tsx b/src/features/graph/GraphPage.tsx
index bfd5dd9..9661ab1 100644
--- a/src/features/graph/GraphPage.tsx
+++ b/src/features/graph/GraphPage.tsx
@@ -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(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 Loading…
+ if (inputs.error) return {inputs.error.message}
+ if (!full || !shown || !flow) return null
+
+ return (
+ <>
+
+
+
+
+
+
+ {inputs.data.notes.map((n) => (
+
+ Incomplete: could not read {n}
+
+ ))}
+
+ Identities → Policies → Paths
+ Identity→policy edges include policies inherited via entities and groups.
+
+ {shown.nodes.length === 0 ? (
+ Nothing matches.
+ ) : (
+
+
+ setSelected({ kind: 'node', id: n.id })}
+ onEdgeClick={(_, e) => setSelected({ kind: 'edge', id: e.id })}
+ onPaneClick={() => setSelected(null)}
+ >
+
+
+
+
+
setSelected(null)} />
+
+ )}
+ >
+ )
+}
+
export function GraphPage() {
- return Access Graph
+ return (
+
+ Access Graph
+ {(client) => }
+
+ )
}
diff --git a/src/features/secrets/AccessPanel.tsx b/src/features/secrets/AccessPanel.tsx
index 677ea5a..d2dab8f 100644
--- a/src/features/secrets/AccessPanel.tsx
+++ b/src/features/secrets/AccessPanel.tsx
@@ -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 (label: string, p: Promise, 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 Loading access…
if (data.error) return Could not load access: {data.error.message}
diff --git a/src/features/shared/useAccessInputs.ts b/src/features/shared/useAccessInputs.ts
new file mode 100644
index 0000000..d0c2082
--- /dev/null
+++ b/src/features/shared/useAccessInputs.ts
@@ -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(label: string, p: Promise, 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 => {
+ 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] : [])),
+ }
+ },
+ })
+}
diff --git a/src/index.css b/src/index.css
index 6cf8e97..43e40b8 100644
--- a/src/index.css
+++ b/src/index.css
@@ -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;
+}
diff --git a/src/model/graphFilter.ts b/src/model/graphFilter.ts
new file mode 100644
index 0000000..952bebf
--- /dev/null
+++ b/src/model/graphFilter.ts
@@ -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, dir: 'down' | 'up'): Set {
+ 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[] = []
+ 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
+}
diff --git a/src/model/graphView.test.ts b/src/model/graphView.test.ts
new file mode 100644
index 0000000..4985aba
--- /dev/null
+++ b/src/model/graphView.test.ts
@@ -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
+ })
+})
diff --git a/src/model/layout.ts b/src/model/layout.ts
new file mode 100644
index 0000000..2976db1
--- /dev/null
+++ b/src/model/layout.ts
@@ -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 {
+ const cols: Record = { 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()
+ 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()
+ 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()
+ 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
+}