Add KV v2 secret browser with per-secret Access panel
Model follows OpenBao's most-specific-path rule rather than unioning matches, verified against sys/capabilities-self in integration tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f2ba697093
commit
cd1438987b
11 files changed
+604
-30
No files matched your search
@@ -0,0 +1,73 @@
|
||||
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
|
||||
import { accessForPath } from '../model/graph'
|
||||
import { resolveIdentities } from '../model/identities'
|
||||
import { pathMatches } from '../model/policy'
|
||||
import { BaoClient } from './bao'
|
||||
import * as secrets from './secrets'
|
||||
import * as tokens from './tokens'
|
||||
|
||||
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 P = { rw: `it-sec-rw-${sfx}`, ro: `it-sec-ro-${sfx}`, deny: `it-sec-deny-${sfx}` }
|
||||
const created: tokens.CreatedToken[] = []
|
||||
|
||||
const policy = (name: string, hcl: string) => client.request('PUT', `sys/policies/acl/${name}`, { policy: hcl })
|
||||
|
||||
beforeAll(async () => {
|
||||
await policy(P.rw, `path "secret/data/it-${sfx}/*" { capabilities = ["create", "read", "update"] }`)
|
||||
await policy(P.ro, `path "secret/data/it-${sfx}/+/pub" { capabilities = ["read", "list"] }`)
|
||||
await policy(P.deny, `path "secret/data/it-${sfx}/private" { capabilities = ["deny"] }`)
|
||||
await client.request('POST', `secret/data/it-${sfx}/app/db`, { data: { k: 'v' } })
|
||||
await client.request('POST', `secret/data/it-${sfx}/team/pub`, { data: { k: 'v' } })
|
||||
for (const [name, policies] of [
|
||||
['a', [P.rw, P.ro]],
|
||||
['b', [P.rw, P.deny]],
|
||||
['c', [P.ro]],
|
||||
] as const) {
|
||||
created.push(await tokens.createToken(client, { displayName: `it-${sfx}-${name}`, policies: [...policies], renewable: false, orphan: false }))
|
||||
}
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
for (const t of created) await tokens.revokeToken(client, t.accessor).catch(() => {})
|
||||
for (const p of Object.values(P)) await client.request('DELETE', `sys/policies/acl/${p}`).catch(() => {})
|
||||
await client.request('DELETE', `secret/metadata/it-${sfx}/app/db`).catch(() => {})
|
||||
await client.request('DELETE', `secret/metadata/it-${sfx}/team/pub`).catch(() => {})
|
||||
})
|
||||
|
||||
describe('secret browser API', () => {
|
||||
test('finds the KV v2 mount and lists folders before secrets', async () => {
|
||||
expect((await secrets.listKvMounts(client)).map((m) => m.path)).toContain('secret/')
|
||||
const top = await secrets.listSecrets(client, 'secret/', `it-${sfx}/`)
|
||||
expect(top.map((e) => [e.name, e.isFolder])).toEqual([
|
||||
['app/', true],
|
||||
['team/', true],
|
||||
])
|
||||
const app = await secrets.listSecrets(client, 'secret/', `it-${sfx}/app/`)
|
||||
expect(app).toEqual([{ name: 'db', path: `it-${sfx}/app/db`, isFolder: false }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('access model vs sys/capabilities-self', () => {
|
||||
test.each([
|
||||
`it-${sfx}/app/db`,
|
||||
`it-${sfx}/private`,
|
||||
`it-${sfx}/team/pub`,
|
||||
`it-${sfx}/team/x/y`,
|
||||
`it-${sfx}/team`,
|
||||
`other-${sfx}/z`,
|
||||
])('agrees for %s', async (secret) => {
|
||||
const names = await client.list('sys/policies/acl')
|
||||
const policies = await Promise.all(names.map(async (name) => ({ name, hcl: await secrets.readPolicyHcl(client, name) })))
|
||||
const identities = resolveIdentities({ users: [], entities: [], groups: [], tokens: await tokens.listTokens(client) })
|
||||
const path = secrets.dataPath('secret/', secret)
|
||||
const model = accessForPath(identities, policies, path, pathMatches)
|
||||
|
||||
for (const t of created) {
|
||||
const info = await tokens.lookupAccessor(client, t.accessor)
|
||||
const real = await secrets.capabilitiesSelf(client.withToken(t.token), path)
|
||||
const predicted = [...new Set(model.filter((m) => m.identity.name === info.display_name).flatMap((m) => m.capabilities))]
|
||||
expect(predicted.length ? predicted.sort() : ['deny'], `${info.display_name} on ${path}`).toEqual([...real].sort())
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { BaoClient } from './bao'
|
||||
|
||||
const enc = (path: string) => path.split('/').map(encodeURIComponent).join('/')
|
||||
|
||||
export interface KvMount {
|
||||
/** Mount path with trailing slash, e.g. "secret/". */
|
||||
path: string
|
||||
}
|
||||
|
||||
export interface SecretEntry {
|
||||
name: string
|
||||
/** Path relative to the mount, e.g. "app/db" (folders keep a trailing slash). */
|
||||
path: string
|
||||
isFolder: boolean
|
||||
}
|
||||
|
||||
export async function listKvMounts(c: BaoClient): Promise<KvMount[]> {
|
||||
const res = await c.request<{ data: Record<string, { type: string; options?: { version?: string } | null }> }>(
|
||||
'GET',
|
||||
'sys/mounts',
|
||||
)
|
||||
return Object.entries(res.data)
|
||||
.filter(([, m]) => m.type === 'kv' && m.options?.version === '2')
|
||||
.map(([path]) => ({ path }))
|
||||
.sort((a, b) => a.path.localeCompare(b.path))
|
||||
}
|
||||
|
||||
/** Lists metadata only; secret values are never read. `prefix` is "" or ends with "/". */
|
||||
export async function listSecrets(c: BaoClient, mount: string, prefix: string): Promise<SecretEntry[]> {
|
||||
const keys = await c.list(`${mount}metadata/${enc(prefix)}`)
|
||||
return keys
|
||||
.map((k) => ({ name: k, path: prefix + k, isFolder: k.endsWith('/') }))
|
||||
.sort((a, b) => Number(b.isFolder) - Number(a.isFolder) || a.name.localeCompare(b.name))
|
||||
}
|
||||
|
||||
/** API path of a secret's data, which is what ACL policies are written against. */
|
||||
export const dataPath = (mount: string, secret: string) => `${mount}data/${secret}`
|
||||
|
||||
export async function readPolicyHcl(c: BaoClient, name: string): Promise<string | null> {
|
||||
try {
|
||||
const res = await c.request<{ data: { policy: string } }>('GET', `sys/policies/acl/${encodeURIComponent(name)}`)
|
||||
return res.data.policy
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** Capabilities of the current token on a path (used to cross-check the access model). */
|
||||
export async function capabilitiesSelf(c: BaoClient, path: string): Promise<string[]> {
|
||||
const res = await c.request<{ capabilities: string[] }>('POST', 'sys/capabilities-self', { paths: [path] })
|
||||
return res.capabilities
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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 { accessForPath } from '../../model/graph'
|
||||
import { resolveIdentities } from '../../model/identities'
|
||||
import { pathMatches } from '../../model/policy'
|
||||
|
||||
interface Props {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
secret: string
|
||||
}
|
||||
|
||||
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] : [])),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (data.isPending) return <p>Loading access…</p>
|
||||
if (data.error) return <p role="alert">Could not load access: {data.error.message}</p>
|
||||
|
||||
const path = dataPath(mount, secret)
|
||||
const entries = accessForPath(data.data.identities, data.data.policies, path, pathMatches)
|
||||
|
||||
return (
|
||||
<section aria-label="Access">
|
||||
<h2>Access to {secret}</h2>
|
||||
<p>
|
||||
Evaluated against <code>{path}</code>
|
||||
</p>
|
||||
{data.data.notes.map((n) => (
|
||||
<p key={n} role="alert">
|
||||
Incomplete: could not read {n}
|
||||
</p>
|
||||
))}
|
||||
{entries.length === 0 ? (
|
||||
<p>No identity can reach this secret.</p>
|
||||
) : (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Identity</th>
|
||||
<th>Type</th>
|
||||
<th>Via policy</th>
|
||||
<th>Capabilities</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((e) => (
|
||||
<tr key={`${e.identity.kind}:${e.identity.name}:${e.policy}`}>
|
||||
<td>{e.identity.name}</td>
|
||||
<td>{e.identity.kind}</td>
|
||||
<td>{e.policy}</td>
|
||||
<td>{e.capabilities.join(', ')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<p className="hint">
|
||||
Only the most specific matching policy path applies, as in OpenBao. Parameter constraints and templated paths are approximated.
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
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 ids from '../../api/identities'
|
||||
import * as api from '../../api/secrets'
|
||||
import { SessionProvider } from '../../api/session'
|
||||
import { useSession } from '../../api/useSession'
|
||||
import * as tokens from '../../api/tokens'
|
||||
import { SecretsPage } from './SecretsPage'
|
||||
|
||||
vi.mock('../../api/identities')
|
||||
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof api>()), listKvMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() }))
|
||||
vi.mock('../../api/tokens')
|
||||
|
||||
const client = new BaoClient('http://b', 't')
|
||||
|
||||
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(api.listKvMounts).mockResolvedValue([{ path: 'secret/' }])
|
||||
vi.mocked(api.listSecrets).mockImplementation(async (_c, _m, prefix) =>
|
||||
prefix === ''
|
||||
? [{ name: 'app/', path: 'app/', isFolder: true }]
|
||||
: [{ name: 'db', path: 'app/db', isFolder: false }],
|
||||
)
|
||||
vi.mocked(ids.listUsers).mockResolvedValue([
|
||||
{ name: 'alice', policies: ['app-rw'], ttl: 0 },
|
||||
{ name: 'bob', policies: ['other'], ttl: 0 },
|
||||
])
|
||||
vi.mocked(ids.listEntities).mockResolvedValue([])
|
||||
vi.mocked(ids.listGroups).mockResolvedValue([])
|
||||
vi.mocked(tokens.listTokens).mockResolvedValue([])
|
||||
vi.mocked(ids.listPolicyNames).mockResolvedValue(['app-rw', 'other'])
|
||||
vi.mocked(api.readPolicyHcl).mockImplementation(async (_c, n) =>
|
||||
n === 'app-rw' ? 'path "secret/data/app/*" { capabilities = ["read", "update"] }' : 'path "secret/data/zzz" { capabilities = ["read"] }',
|
||||
)
|
||||
})
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
test('navigates folders and shows who can reach a secret', async () => {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<SessionProvider>
|
||||
<MemoryRouter>
|
||||
<Connected />
|
||||
<SecretsPage />
|
||||
</MemoryRouter>
|
||||
</SessionProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'go' }))
|
||||
await user.click(await screen.findByRole('button', { name: /app\// }))
|
||||
await user.click(await screen.findByRole('button', { name: /db/ }))
|
||||
|
||||
const panel = await screen.findByRole('region', { name: 'Access' })
|
||||
const row = (await within(panel).findByText('alice')).closest('tr')!
|
||||
expect(within(row).getByText('app-rw')).toBeInTheDocument()
|
||||
expect(within(row).getByText('read, update')).toBeInTheDocument()
|
||||
expect(within(panel).queryByText('bob')).not.toBeInTheDocument()
|
||||
expect(within(panel).getByText('secret/data/app/db')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('asks to connect first', () => {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<SessionProvider>
|
||||
<MemoryRouter>
|
||||
<SecretsPage />
|
||||
</MemoryRouter>
|
||||
</SessionProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText(/Not connected/)).toBeInTheDocument()
|
||||
})
|
||||
@@ -1,3 +1,85 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { listKvMounts, listSecrets } from '../../api/secrets'
|
||||
import { RequireConnection } from '../shared/RequireConnection'
|
||||
import { AccessPanel } from './AccessPanel'
|
||||
|
||||
function Browser({ client }: { client: BaoClient }) {
|
||||
const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) })
|
||||
const [mountChoice, setMount] = useState<string | null>(null)
|
||||
const [prefix, setPrefix] = useState('')
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
|
||||
const mount = mountChoice ?? mounts.data?.[0]?.path ?? null
|
||||
const entries = useQuery({
|
||||
queryKey: ['kv-list', mount, prefix],
|
||||
queryFn: () => listSecrets(client, mount!, prefix),
|
||||
enabled: mount !== null,
|
||||
})
|
||||
|
||||
const crumbs = prefix.split('/').filter(Boolean)
|
||||
const go = (p: string) => {
|
||||
setPrefix(p)
|
||||
setSelected(null)
|
||||
}
|
||||
|
||||
if (mounts.error) return <p role="alert">{mounts.error.message}</p>
|
||||
if (mounts.isPending) return <p>Loading…</p>
|
||||
if (!mount) return <p>No KV v2 secrets engines are mounted.</p>
|
||||
|
||||
return (
|
||||
<>
|
||||
<label>
|
||||
Mount
|
||||
<select
|
||||
value={mount}
|
||||
onChange={(e) => {
|
||||
setMount(e.target.value)
|
||||
go('')
|
||||
}}
|
||||
>
|
||||
{mounts.data.map((m) => (
|
||||
<option key={m.path}>{m.path}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<nav aria-label="Path" className="crumbs">
|
||||
<button type="button" onClick={() => go('')}>
|
||||
{mount}
|
||||
</button>
|
||||
{crumbs.map((c, i) => (
|
||||
<button key={i} type="button" onClick={() => go(crumbs.slice(0, i + 1).join('/') + '/')}>
|
||||
{c}/
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{entries.error && <p role="alert">{entries.error.message}</p>}
|
||||
{entries.data?.length === 0 && <p>Nothing here.</p>}
|
||||
<ul className="entries">
|
||||
{entries.data?.map((e) => (
|
||||
<li key={e.path}>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={selected === e.path}
|
||||
onClick={() => (e.isFolder ? go(e.path) : setSelected(e.path))}
|
||||
>
|
||||
{e.isFolder ? '📁 ' : '🔑 '}
|
||||
{e.name}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{selected && <AccessPanel client={client} mount={mount} secret={selected} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function SecretsPage() {
|
||||
return <h1>Secrets</h1>
|
||||
return (
|
||||
<section>
|
||||
<h1>Secrets</h1>
|
||||
<RequireConnection>{(client) => <Browser client={client} />}</RequireConnection>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -82,3 +82,24 @@ label.check {
|
||||
margin-bottom: 1rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.crumbs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
|
||||
.entries {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.entries [aria-pressed='true'] {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.hint {
|
||||
opacity: 0.7;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
+11
-12
@@ -1,4 +1,4 @@
|
||||
import { CAPABILITIES, parsePolicy, type Capability, type PolicyRule } from './policy'
|
||||
import { CAPABILITIES, parsePolicy, winningRules, type Capability, type PolicyRule } from './policy'
|
||||
|
||||
export const MANAGED_PREFIX = 'envbao-'
|
||||
|
||||
@@ -134,7 +134,7 @@ export function buildAccessGraph(identities: Identity[], policies: PolicyInput[]
|
||||
return { nodes: [...nodes.values()], edges: [...edges.values()] }
|
||||
}
|
||||
|
||||
/** Who can reach `secretPath`, and through which policy? Deny wins within a policy set per identity. */
|
||||
/** Who can reach `secretPath`, and through which policies? Mirrors OpenBao: one winning path per identity, deny wins. */
|
||||
export interface AccessEntry {
|
||||
identity: Identity
|
||||
policy: string
|
||||
@@ -145,22 +145,21 @@ export function accessForPath(
|
||||
identities: Identity[],
|
||||
policies: PolicyInput[],
|
||||
secretPath: string,
|
||||
// Kept as a parameter so callers/tests can substitute the matcher.
|
||||
match: (rulePath: string, target: string) => boolean,
|
||||
): AccessEntry[] {
|
||||
const byName = new Map(policies.map((p) => [p.name, p]))
|
||||
const out: AccessEntry[] = []
|
||||
for (const identity of identities) {
|
||||
const denied = identity.policies.some((n) => {
|
||||
const p = byName.get(n)
|
||||
return p && rulesFor(p).rules.some((r) => r.capabilities.includes('deny') && match(r.path, secretPath))
|
||||
const tagged = [...new Set(identity.policies)].flatMap((name) => {
|
||||
const p = byName.get(name) ?? (name === 'root' ? { name, hcl: null } : undefined)
|
||||
return p ? rulesFor(p).rules.filter((r) => match(r.path, secretPath)).map((r) => ({ ...r, policy: name })) : []
|
||||
})
|
||||
if (denied) continue
|
||||
for (const name of new Set(identity.policies)) {
|
||||
const p = byName.get(name)
|
||||
if (!p) continue
|
||||
const caps = new Set<Capability>()
|
||||
for (const r of rulesFor(p).rules) if (match(r.path, secretPath)) r.capabilities.forEach((c) => caps.add(c))
|
||||
if (caps.size) out.push({ identity, policy: name, capabilities: [...caps] })
|
||||
const winners = winningRules(tagged, secretPath)
|
||||
if (winners.some((r) => r.capabilities.includes('deny'))) continue
|
||||
for (const policy of new Set(winners.map((r) => r.policy))) {
|
||||
const caps = new Set(winners.filter((r) => r.policy === policy).flatMap((r) => r.capabilities))
|
||||
if (caps.size) out.push({ identity, policy, capabilities: [...caps] })
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, test } from 'vitest'
|
||||
import { resolveIdentities } from './identities'
|
||||
|
||||
const entity = (over = {}) => ({
|
||||
id: 'e1',
|
||||
name: 'alice-entity',
|
||||
policies: ['ent'],
|
||||
disabled: false,
|
||||
aliases: [{ id: 'a1', name: 'alice', mount_accessor: 'x', mount_path: 'auth/userpass/' }],
|
||||
...over,
|
||||
})
|
||||
|
||||
test('user inherits aliased entity and group policies', () => {
|
||||
const ids = resolveIdentities({
|
||||
users: [{ name: 'alice', policies: ['own'], ttl: 0 }],
|
||||
entities: [entity()],
|
||||
groups: [{ id: 'g1', name: 'devs', policies: ['grp'], member_entity_ids: ['e1'] }],
|
||||
tokens: [],
|
||||
})
|
||||
expect(ids.find((i) => i.kind === 'user')?.policies.sort()).toEqual(['ent', 'grp', 'own'])
|
||||
expect(ids.find((i) => i.kind === 'entity')?.policies.sort()).toEqual(['ent', 'grp'])
|
||||
expect(ids.find((i) => i.kind === 'group')?.policies).toEqual(['grp'])
|
||||
})
|
||||
|
||||
test('disabled entities and aliases on other mounts are not inherited', () => {
|
||||
const users = [{ name: 'alice', policies: ['own'], ttl: 0 }]
|
||||
const disabled = resolveIdentities({ users, entities: [entity({ disabled: true })], groups: [], tokens: [] })
|
||||
expect(disabled.find((i) => i.kind === 'user')?.policies).toEqual(['own'])
|
||||
|
||||
const other = entity({ aliases: [{ id: 'a', name: 'alice', mount_accessor: 'x', mount_path: 'auth/ldap/' }] })
|
||||
const res = resolveIdentities({ users, entities: [other], groups: [], tokens: [] })
|
||||
expect(res.find((i) => i.kind === 'user')?.policies).toEqual(['own'])
|
||||
})
|
||||
|
||||
test('tokens are named by display name, falling back to accessor', () => {
|
||||
const t = { accessor: 'acc', display_name: '', policies: ['p'], ttl: 0, renewable: false, orphan: false, creation_time: '', expire_time: null }
|
||||
const res = resolveIdentities({ users: [], entities: [], groups: [], tokens: [t, { ...t, display_name: 'token-ci' }] })
|
||||
expect(res.map((i) => i.name)).toEqual(['acc', 'token-ci'])
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Entity, Group, UserpassUser } from '../api/identities'
|
||||
import type { TokenSummary } from '../api/tokens'
|
||||
import type { Identity } from './graph'
|
||||
|
||||
interface Sources {
|
||||
users: UserpassUser[]
|
||||
entities: Entity[]
|
||||
groups: Group[]
|
||||
tokens: TokenSummary[]
|
||||
}
|
||||
|
||||
const USERPASS_MOUNT = 'auth/userpass/'
|
||||
|
||||
/**
|
||||
* Flatten OpenBao's identity sources into the graph's Identity list.
|
||||
* A userpass user's effective policies are its own plus those of any entity aliased
|
||||
* to it and the groups that entity belongs to, which is what the token it logs in
|
||||
* with receives. Entities also include their groups' policies.
|
||||
*/
|
||||
export function resolveIdentities({ users, entities, groups, tokens }: Sources): Identity[] {
|
||||
const groupPolicies = (entityId: string) =>
|
||||
groups.filter((g) => g.member_entity_ids.includes(entityId)).flatMap((g) => g.policies)
|
||||
|
||||
const out: Identity[] = []
|
||||
|
||||
for (const u of users) {
|
||||
const entity = entities.find((e) => !e.disabled && e.aliases.some((a) => a.name === u.name && a.mount_path === USERPASS_MOUNT))
|
||||
const policies = [...u.policies, ...(entity ? [...entity.policies, ...groupPolicies(entity.id)] : [])]
|
||||
out.push({ kind: 'user', name: u.name, policies: [...new Set(policies)] })
|
||||
}
|
||||
for (const e of entities) {
|
||||
out.push({ kind: 'entity', name: e.name, policies: [...new Set([...e.policies, ...groupPolicies(e.id)])] })
|
||||
}
|
||||
for (const g of groups) out.push({ kind: 'group', name: g.name, policies: g.policies })
|
||||
for (const t of tokens) {
|
||||
out.push({ kind: 'token', name: t.display_name || t.accessor, policies: t.policies })
|
||||
}
|
||||
return out
|
||||
}
|
||||
+66
-13
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { accessForPath, buildAccessGraph, type Identity } from './graph'
|
||||
import { parseHcl } from './hcl'
|
||||
import { effectiveCapabilities, parsePolicy, pathMatches } from './policy'
|
||||
import { comparePriority, effectiveCapabilities, parsePolicy, pathMatches } from './policy'
|
||||
|
||||
describe('parseHcl', () => {
|
||||
test('parses comments, blocks and values', () => {
|
||||
@@ -88,19 +88,53 @@ describe('pathMatches', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('effectiveCapabilities', () => {
|
||||
test('unions matching rules and deny wins', () => {
|
||||
const rules = parsePolicy(`
|
||||
path "s/*" { capabilities = ["read", "list"] }
|
||||
path "s/a" { capabilities = ["update"] }
|
||||
path "s/secret" { capabilities = ["deny"] }
|
||||
`).rules
|
||||
expect(effectiveCapabilities(rules, 's/a').sort()).toEqual(['list', 'read', 'update'])
|
||||
expect(effectiveCapabilities(rules, 's/secret')).toEqual(['deny'])
|
||||
expect(effectiveCapabilities(rules, 'other')).toEqual([])
|
||||
describe('comparePriority', () => {
|
||||
test.each([
|
||||
// [higher, lower]
|
||||
['s/exact', 's/*'],
|
||||
['s/a/*', 's/*'],
|
||||
['s/a/+', 's/+/b'],
|
||||
['s/a/b*', 's/a/*'],
|
||||
['s/+/b', 's/*'],
|
||||
['s/+/+/c', 's/+/+/*'],
|
||||
['s/a/+/c', 's/a/+/+'],
|
||||
['s/a/bb', 's/a/b'],
|
||||
['s/b', 's/a'],
|
||||
])('%s outranks %s', (hi, lo) => {
|
||||
expect(comparePriority(hi, lo)).toBeGreaterThan(0)
|
||||
expect(comparePriority(lo, hi)).toBeLessThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('effectiveCapabilities', () => {
|
||||
const rules = parsePolicy(`
|
||||
path "s/*" { capabilities = ["read", "list"] }
|
||||
path "s/a" { capabilities = ["update"] }
|
||||
path "s/secret" { capabilities = ["deny"] }
|
||||
path "s/+/pub" { capabilities = ["read"] }
|
||||
`).rules
|
||||
|
||||
test('the most specific rule wins and rules are not unioned', () => {
|
||||
expect(effectiveCapabilities(rules, 's/a')).toEqual(['update'])
|
||||
expect(effectiveCapabilities(rules, 's/other').sort()).toEqual(['list', 'read'])
|
||||
expect(effectiveCapabilities(rules, 's/x/pub')).toEqual(['read'])
|
||||
})
|
||||
|
||||
test('deny at the winning path wins; a broader deny does not override a specific grant', () => {
|
||||
expect(effectiveCapabilities(rules, 's/secret')).toEqual(['deny'])
|
||||
const r = parsePolicy('path "s/*" { capabilities = ["deny"] }\npath "s/ok" { capabilities = ["read"] }').rules
|
||||
expect(effectiveCapabilities(r, 's/ok')).toEqual(['read'])
|
||||
expect(effectiveCapabilities(r, 's/no')).toEqual(['deny'])
|
||||
})
|
||||
|
||||
test('identical paths from different rules are merged', () => {
|
||||
const r = parsePolicy('path "s/a" { capabilities = ["read"] }\npath "s/a" { capabilities = ["update"] }').rules
|
||||
expect(effectiveCapabilities(r, 's/a').sort()).toEqual(['read', 'update'])
|
||||
})
|
||||
|
||||
test('no match is empty', () => expect(effectiveCapabilities(rules, 'other')).toEqual([]))
|
||||
})
|
||||
|
||||
describe('buildAccessGraph', () => {
|
||||
const alice: Identity = { kind: 'user', name: 'alice', policies: ['envbao-alice', 'default'] }
|
||||
const bob: Identity = { kind: 'token', name: 'ci', policies: ['envbao-alice', 'ghost'] }
|
||||
@@ -182,9 +216,28 @@ describe('accessForPath', () => {
|
||||
{ kind: 'user', name: 'c', policies: ['ro'] },
|
||||
]
|
||||
|
||||
test('lists identities with access, honouring deny', () => {
|
||||
test('the most specific path wins per identity, and deny at that path removes access', () => {
|
||||
const res = accessForPath(ids, policies, 'secret/data/app/db', pathMatches)
|
||||
expect(res.map((r) => `${r.identity.name}:${r.policy}`)).toEqual(['a:rw', 'a:ro', 'c:ro'])
|
||||
// a: exact `app/db` (ro) outranks the `app/*` glob (rw), so only read; b: exact deny; c: ro
|
||||
expect(res.map((r) => `${r.identity.name}:${r.policy}:${r.capabilities.join()}`)).toEqual(['a:ro:read', 'c:ro:read'])
|
||||
})
|
||||
|
||||
test('falls back to the glob where no more specific rule matches', () => {
|
||||
const res = accessForPath(ids, policies, 'secret/data/app/other', pathMatches)
|
||||
expect(res.map((r) => `${r.identity.name}:${r.policy}`)).toEqual(['a:rw', 'b:rw'])
|
||||
})
|
||||
|
||||
test('a broader deny does not override a more specific grant', () => {
|
||||
const res = accessForPath(
|
||||
[{ kind: 'user', name: 'd', policies: ['wide-deny', 'narrow'] }],
|
||||
[
|
||||
{ name: 'wide-deny', hcl: 'path "s/*" { capabilities = ["deny"] }' },
|
||||
{ name: 'narrow', hcl: 'path "s/ok" { capabilities = ["read"] }' },
|
||||
],
|
||||
's/ok',
|
||||
pathMatches,
|
||||
)
|
||||
expect(res).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('returns nothing for unrelated paths', () => {
|
||||
|
||||
+40
-4
@@ -107,11 +107,47 @@ function segmentMatches(pattern: string, segment: string): boolean {
|
||||
return pattern === segment
|
||||
}
|
||||
|
||||
/** Effective capabilities of a set of rules on a concrete path; `deny` wins. */
|
||||
const normalised = (path: string) => path.replace(/\{\{[^}]*\}\}/g, '+')
|
||||
|
||||
/**
|
||||
* OpenBao picks ONE winning path among the rules that match, it does not merge them
|
||||
* (rules with the identical path string, e.g. from different policies, are merged).
|
||||
* Priority, highest first: first wildcard (+ or *) later in the path; non-glob over
|
||||
* trailing-`*` glob; fewer `+` segments; longer path; lexicographically larger.
|
||||
* Returns >0 if `a` outranks `b`.
|
||||
*/
|
||||
export function comparePriority(a: string, b: string): number {
|
||||
const na = normalised(a)
|
||||
const nb = normalised(b)
|
||||
const wild = (p: string) => {
|
||||
const i = p.search(/[+*]/)
|
||||
return i < 0 ? Infinity : i
|
||||
}
|
||||
if (wild(na) !== wild(nb)) return wild(na) > wild(nb) ? 1 : -1
|
||||
const globA = na.endsWith('*')
|
||||
const globB = nb.endsWith('*')
|
||||
if (globA !== globB) return globA ? -1 : 1
|
||||
const plus = (p: string) => p.split('/').filter((x) => x === '+').length
|
||||
if (plus(na) !== plus(nb)) return plus(na) < plus(nb) ? 1 : -1
|
||||
if (na.length !== nb.length) return na.length > nb.length ? 1 : -1
|
||||
return na === nb ? 0 : na > nb ? 1 : -1
|
||||
}
|
||||
|
||||
/** The rules at the single winning path for `target` (several when policies repeat that path). */
|
||||
export function winningRules<T extends { path: string }>(rules: T[], target: string): T[] {
|
||||
let best: T[] = []
|
||||
for (const r of rules) {
|
||||
if (!pathMatches(r.path, target)) continue
|
||||
const c = best.length ? comparePriority(r.path, best[0].path) : 1
|
||||
if (c > 0) best = [r]
|
||||
else if (c === 0) best.push(r)
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Effective capabilities on a concrete path; `deny` wins at the winning path. */
|
||||
export function effectiveCapabilities(rules: PolicyRule[], target: string): Capability[] {
|
||||
const caps = new Set<Capability>()
|
||||
for (const r of rules) {
|
||||
if (pathMatches(r.path, target)) r.capabilities.forEach((c) => caps.add(c))
|
||||
}
|
||||
for (const r of winningRules(rules, target)) r.capabilities.forEach((c) => caps.add(c))
|
||||
return caps.has('deny') ? ['deny'] : [...caps]
|
||||
}
|
||||
Reference in new issue
Block a user