Add KV v2 secret browser with per-secret Access panel
CI / integration (push) Successful in 11s
CI / check (push) Successful in 13s

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:
mattandClaude Sonnet 5.5 committed 2026-10-20 11:26:33 +01:00
1 parent f2ba697093
commit cd1438987b
11 files changed
+604 -30

No files matched your search

+11 -12
View File
@@ -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
+39
View File
@@ -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'])
})
+39
View File
@@ -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
View File
@@ -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
View File
@@ -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]
}