Add HCL policy parser and access-graph model; fix build types
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ac4307ebc8
commit
cc81f88a04
5 files changed
+645
-1
No files matched your search
@@ -0,0 +1,167 @@
|
||||
import { CAPABILITIES, parsePolicy, type Capability, type PolicyRule } from './policy'
|
||||
|
||||
export const MANAGED_PREFIX = 'envbao-'
|
||||
|
||||
export type IdentityKind = 'user' | 'token' | 'entity' | 'group'
|
||||
|
||||
export interface Identity {
|
||||
kind: IdentityKind
|
||||
name: string
|
||||
policies: string[]
|
||||
}
|
||||
|
||||
/** `hcl: null` for a policy that is referenced by an identity but could not be fetched. */
|
||||
export interface PolicyInput {
|
||||
name: string
|
||||
hcl: string | null
|
||||
}
|
||||
|
||||
export interface IdentityNode {
|
||||
id: string
|
||||
type: 'identity'
|
||||
kind: IdentityKind
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface PolicyNode {
|
||||
id: string
|
||||
type: 'policy'
|
||||
label: string
|
||||
managed: boolean
|
||||
/** Referenced by an identity but not present in the policy list. */
|
||||
missing: boolean
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export interface PathNode {
|
||||
id: string
|
||||
type: 'path'
|
||||
label: string
|
||||
}
|
||||
|
||||
export type GraphNode = IdentityNode | PolicyNode | PathNode
|
||||
|
||||
export interface GraphEdge {
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
/** Present on policy -> path edges only. */
|
||||
capabilities?: Capability[]
|
||||
warnings?: string[]
|
||||
}
|
||||
|
||||
export interface AccessGraph {
|
||||
nodes: GraphNode[]
|
||||
edges: GraphEdge[]
|
||||
}
|
||||
|
||||
export const identityId = (i: Pick<Identity, 'kind' | 'name'>) => `identity:${i.kind}:${i.name}`
|
||||
export const policyId = (name: string) => `policy:${name}`
|
||||
export const pathId = (path: string) => `path:${path}`
|
||||
|
||||
export const isManagedPolicy = (name: string) => name.startsWith(MANAGED_PREFIX)
|
||||
|
||||
/** The built-in root policy is not HCL; it allows everything. */
|
||||
const ROOT_RULES: PolicyRule[] = [
|
||||
{
|
||||
path: '*',
|
||||
capabilities: CAPABILITIES.filter((c) => c !== 'deny'),
|
||||
warnings: ['Root policy: unrestricted access'],
|
||||
},
|
||||
]
|
||||
|
||||
export function rulesFor(policy: PolicyInput): { rules: PolicyRule[]; warnings: string[] } {
|
||||
if (policy.name === 'root') return { rules: ROOT_RULES, warnings: [] }
|
||||
if (policy.hcl === null) return { rules: [], warnings: [] }
|
||||
return parsePolicy(policy.hcl)
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity -> Policy -> Path graph. Pure: callers fetch identities and policies.
|
||||
* Policies no identity uses are included so unattached grants stay visible.
|
||||
*/
|
||||
export function buildAccessGraph(identities: Identity[], policies: PolicyInput[]): AccessGraph {
|
||||
const nodes = new Map<string, GraphNode>()
|
||||
const edges = new Map<string, GraphEdge>()
|
||||
const byName = new Map(policies.map((p) => [p.name, p]))
|
||||
|
||||
const addPolicy = (name: string) => {
|
||||
const id = policyId(name)
|
||||
if (nodes.has(id)) return
|
||||
// root is built in and never appears in the policy list
|
||||
const input = byName.get(name) ?? (name === 'root' ? { name, hcl: null } : undefined)
|
||||
const { rules, warnings } = input ? rulesFor(input) : { rules: [], warnings: [] }
|
||||
nodes.set(id, {
|
||||
id,
|
||||
type: 'policy',
|
||||
label: name,
|
||||
managed: isManagedPolicy(name),
|
||||
missing: !input,
|
||||
warnings: [...warnings, ...rules.flatMap((r) => r.warnings.map((w) => `${r.path}: ${w}`))],
|
||||
})
|
||||
for (const rule of rules) {
|
||||
const pid = pathId(rule.path)
|
||||
if (!nodes.has(pid)) nodes.set(pid, { id: pid, type: 'path', label: rule.path })
|
||||
const eid = `${id}->${pid}`
|
||||
const existing = edges.get(eid)
|
||||
if (existing) {
|
||||
// Same path declared twice in one policy: OpenBao unions the capabilities.
|
||||
existing.capabilities = [...new Set([...(existing.capabilities ?? []), ...rule.capabilities])]
|
||||
existing.warnings = [...(existing.warnings ?? []), ...rule.warnings]
|
||||
} else {
|
||||
edges.set(eid, {
|
||||
id: eid,
|
||||
source: id,
|
||||
target: pid,
|
||||
capabilities: [...rule.capabilities],
|
||||
warnings: rule.warnings.length ? [...rule.warnings] : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const identity of identities) {
|
||||
const id = identityId(identity)
|
||||
nodes.set(id, { id, type: 'identity', kind: identity.kind, label: identity.name })
|
||||
for (const name of new Set(identity.policies)) {
|
||||
addPolicy(name)
|
||||
const eid = `${id}->${policyId(name)}`
|
||||
edges.set(eid, { id: eid, source: id, target: policyId(name) })
|
||||
}
|
||||
}
|
||||
for (const p of policies) addPolicy(p.name)
|
||||
|
||||
return { nodes: [...nodes.values()], edges: [...edges.values()] }
|
||||
}
|
||||
|
||||
/** Who can reach `secretPath`, and through which policy? Deny wins within a policy set per identity. */
|
||||
export interface AccessEntry {
|
||||
identity: Identity
|
||||
policy: string
|
||||
capabilities: Capability[]
|
||||
}
|
||||
|
||||
export function accessForPath(
|
||||
identities: Identity[],
|
||||
policies: PolicyInput[],
|
||||
secretPath: string,
|
||||
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))
|
||||
})
|
||||
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] })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Minimal HCL parser: enough for OpenBao ACL policies (blocks, attributes,
|
||||
// strings, numbers, bools, lists, objects, comments). Not a general HCL parser.
|
||||
|
||||
export type HclValue = string | number | boolean | HclValue[] | { [key: string]: HclValue }
|
||||
|
||||
export interface HclBlock {
|
||||
type: string
|
||||
labels: string[]
|
||||
body: HclBody
|
||||
}
|
||||
|
||||
export interface HclBody {
|
||||
attributes: Record<string, HclValue>
|
||||
blocks: HclBlock[]
|
||||
}
|
||||
|
||||
export class HclSyntaxError extends Error {
|
||||
readonly line: number
|
||||
constructor(message: string, line: number) {
|
||||
super(`${message} (line ${line})`)
|
||||
this.name = 'HclSyntaxError'
|
||||
this.line = line
|
||||
}
|
||||
}
|
||||
|
||||
type Token =
|
||||
| { t: 'ident' | 'string' | 'number'; v: string; line: number }
|
||||
| { t: 'punct'; v: '{' | '}' | '[' | ']' | '=' | ','; line: number }
|
||||
| { t: 'eof'; v: ''; line: number }
|
||||
|
||||
function tokenize(src: string): Token[] {
|
||||
const out: Token[] = []
|
||||
let i = 0
|
||||
let line = 1
|
||||
while (i < src.length) {
|
||||
const c = src[i]
|
||||
if (c === '\n') {
|
||||
line++
|
||||
i++
|
||||
} else if (/\s/.test(c)) {
|
||||
i++
|
||||
} else if (c === '#' || (c === '/' && src[i + 1] === '/')) {
|
||||
while (i < src.length && src[i] !== '\n') i++
|
||||
} else if (c === '/' && src[i + 1] === '*') {
|
||||
const end = src.indexOf('*/', i + 2)
|
||||
if (end < 0) throw new HclSyntaxError('Unterminated comment', line)
|
||||
line += src.slice(i, end).split('\n').length - 1
|
||||
i = end + 2
|
||||
} else if (c === '"') {
|
||||
let s = ''
|
||||
i++
|
||||
for (;;) {
|
||||
if (i >= src.length || src[i] === '\n') throw new HclSyntaxError('Unterminated string', line)
|
||||
if (src[i] === '"') break
|
||||
if (src[i] === '\\') {
|
||||
const n = src[i + 1]
|
||||
s += n === 'n' ? '\n' : n === 't' ? '\t' : n
|
||||
i += 2
|
||||
} else s += src[i++]
|
||||
}
|
||||
i++
|
||||
out.push({ t: 'string', v: s, line })
|
||||
} else if ('{}[]=,'.includes(c)) {
|
||||
out.push({ t: 'punct', v: c as '{', line })
|
||||
i++
|
||||
} else if (/[0-9-]/.test(c)) {
|
||||
const m = /^-?[0-9]+(\.[0-9]+)?/.exec(src.slice(i))
|
||||
if (!m) throw new HclSyntaxError(`Unexpected character "${c}"`, line)
|
||||
out.push({ t: 'number', v: m[0], line })
|
||||
i += m[0].length
|
||||
} else if (/[A-Za-z_]/.test(c)) {
|
||||
const m = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(src.slice(i))!
|
||||
out.push({ t: 'ident', v: m[0], line })
|
||||
i += m[0].length
|
||||
} else {
|
||||
throw new HclSyntaxError(`Unexpected character "${c}"`, line)
|
||||
}
|
||||
}
|
||||
out.push({ t: 'eof', v: '', line })
|
||||
return out
|
||||
}
|
||||
|
||||
class Parser {
|
||||
private pos = 0
|
||||
private readonly tokens: Token[]
|
||||
constructor(tokens: Token[]) {
|
||||
this.tokens = tokens
|
||||
}
|
||||
|
||||
private peek(): Token {
|
||||
return this.tokens[this.pos]
|
||||
}
|
||||
private next(): Token {
|
||||
return this.tokens[this.pos++]
|
||||
}
|
||||
private isPunct(v: string): boolean {
|
||||
const t = this.peek()
|
||||
return t.t === 'punct' && t.v === v
|
||||
}
|
||||
private expectPunct(v: string): void {
|
||||
const t = this.next()
|
||||
if (t.t !== 'punct' || t.v !== v) throw new HclSyntaxError(`Expected "${v}"`, t.line)
|
||||
}
|
||||
|
||||
parseBody(closing: boolean): HclBody {
|
||||
const body: HclBody = { attributes: {}, blocks: [] }
|
||||
for (;;) {
|
||||
if (this.peek().t === 'eof') {
|
||||
if (closing) throw new HclSyntaxError('Missing closing "}"', this.peek().line)
|
||||
return body
|
||||
}
|
||||
if (closing && this.isPunct('}')) {
|
||||
this.next()
|
||||
return body
|
||||
}
|
||||
const key = this.next()
|
||||
if (key.t !== 'ident' && key.t !== 'string') throw new HclSyntaxError(`Unexpected "${key.v}"`, key.line)
|
||||
if (this.isPunct('=')) {
|
||||
this.next()
|
||||
body.attributes[key.v] = this.parseValue()
|
||||
continue
|
||||
}
|
||||
const labels: string[] = []
|
||||
while (this.peek().t === 'string') labels.push(this.next().v)
|
||||
this.expectPunct('{')
|
||||
body.blocks.push({ type: key.v, labels, body: this.parseBody(true) })
|
||||
}
|
||||
}
|
||||
|
||||
private parseValue(): HclValue {
|
||||
const t = this.next()
|
||||
if (t.t === 'string') return t.v
|
||||
if (t.t === 'number') return Number(t.v)
|
||||
if (t.t === 'ident') {
|
||||
if (t.v === 'true') return true
|
||||
if (t.v === 'false') return false
|
||||
throw new HclSyntaxError(`Unsupported expression "${t.v}"`, t.line)
|
||||
}
|
||||
if (t.t === 'punct' && t.v === '[') {
|
||||
const items: HclValue[] = []
|
||||
while (!this.isPunct(']')) {
|
||||
items.push(this.parseValue())
|
||||
if (this.isPunct(',')) this.next()
|
||||
else if (!this.isPunct(']')) throw new HclSyntaxError('Expected "," or "]"', this.peek().line)
|
||||
}
|
||||
this.next()
|
||||
return items
|
||||
}
|
||||
if (t.t === 'punct' && t.v === '{') {
|
||||
const obj: { [key: string]: HclValue } = {}
|
||||
while (!this.isPunct('}')) {
|
||||
const k = this.next()
|
||||
if (k.t !== 'ident' && k.t !== 'string') throw new HclSyntaxError(`Unexpected "${k.v}"`, k.line)
|
||||
if (this.isPunct('=')) this.next()
|
||||
obj[k.v] = this.parseValue()
|
||||
if (this.isPunct(',')) this.next()
|
||||
}
|
||||
this.next()
|
||||
return obj
|
||||
}
|
||||
throw new HclSyntaxError(`Unexpected "${t.v}"`, t.line)
|
||||
}
|
||||
}
|
||||
|
||||
export function parseHcl(src: string): HclBody {
|
||||
return new Parser(tokenize(src)).parseBody(false)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { accessForPath, buildAccessGraph, type Identity } from './graph'
|
||||
import { parseHcl } from './hcl'
|
||||
import { effectiveCapabilities, parsePolicy, pathMatches } from './policy'
|
||||
|
||||
describe('parseHcl', () => {
|
||||
test('parses comments, blocks and values', () => {
|
||||
const body = parseHcl(`
|
||||
# comment
|
||||
// another
|
||||
/* block
|
||||
comment */
|
||||
path "a/b" {
|
||||
capabilities = ["read", "list"]
|
||||
flag = true
|
||||
n = 3
|
||||
}
|
||||
`)
|
||||
expect(body.blocks).toHaveLength(1)
|
||||
expect(body.blocks[0].labels).toEqual(['a/b'])
|
||||
expect(body.blocks[0].body.attributes).toEqual({ capabilities: ['read', 'list'], flag: true, n: 3 })
|
||||
})
|
||||
|
||||
test('reports line numbers for syntax errors', () => {
|
||||
expect(() => parseHcl('path "a" {\n capabilities = [\n')).toThrow(/line/)
|
||||
})
|
||||
|
||||
test('handles nested objects and escapes', () => {
|
||||
const body = parseHcl('path "x" { allowed_parameters = { "k" = ["a\\"b"] } }')
|
||||
expect(body.blocks[0].body.attributes.allowed_parameters).toEqual({ k: ['a"b'] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parsePolicy', () => {
|
||||
test('extracts path rules', () => {
|
||||
const p = parsePolicy(`
|
||||
path "secret/data/app/*" { capabilities = ["read", "list"] }
|
||||
path "secret/data/db" { capabilities = ["create", "update", "read"] }
|
||||
`)
|
||||
expect(p.warnings).toEqual([])
|
||||
expect(p.rules.map((r) => [r.path, r.capabilities])).toEqual([
|
||||
['secret/data/app/*', ['read', 'list']],
|
||||
['secret/data/db', ['create', 'update', 'read']],
|
||||
])
|
||||
})
|
||||
|
||||
test('returns a warning instead of throwing on bad syntax', () => {
|
||||
const p = parsePolicy('path "x" {')
|
||||
expect(p.rules).toEqual([])
|
||||
expect(p.warnings[0]).toMatch(/Could not parse/)
|
||||
})
|
||||
|
||||
test('flags constraints, unknown capabilities, templating and unknown blocks', () => {
|
||||
const p = parsePolicy(`
|
||||
path "secret/data/{{identity.entity.name}}/*" { capabilities = ["read", "bogus"] }
|
||||
path "x" {
|
||||
capabilities = ["update"]
|
||||
allowed_parameters = { "foo" = [] }
|
||||
}
|
||||
other "y" {}
|
||||
`)
|
||||
expect(p.rules[0].warnings).toEqual(['Unknown capability "bogus"', 'Templated path is approximated'])
|
||||
expect(p.rules[1].warnings[0]).toMatch(/allowed_parameters/)
|
||||
expect(p.warnings).toEqual(['Ignored unsupported block "other"'])
|
||||
})
|
||||
|
||||
test('dedupes capabilities', () => {
|
||||
expect(parsePolicy('path "a" { capabilities = ["read", "read"] }').rules[0].capabilities).toEqual(['read'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('pathMatches', () => {
|
||||
test.each([
|
||||
['secret/data/a', 'secret/data/a', true],
|
||||
['secret/data/a', 'secret/data/b', false],
|
||||
['secret/data/*', 'secret/data/a', true],
|
||||
['secret/data/*', 'secret/data/a/b/c', true],
|
||||
['secret/data/*', 'secret/data', false],
|
||||
['secret/data/app*', 'secret/data/application', true],
|
||||
['secret/data/app*', 'secret/data/other', false],
|
||||
['secret/+/a', 'secret/x/a', true],
|
||||
['secret/+/a', 'secret/x/y/a', false],
|
||||
['secret/+/*', 'secret/x/y/z', true],
|
||||
['*', 'anything/at/all', true],
|
||||
['secret/data/{{identity.entity.name}}/*', 'secret/data/alice/k', true],
|
||||
])('%s vs %s -> %s', (rule, target, expected) => {
|
||||
expect(pathMatches(rule, target)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
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('buildAccessGraph', () => {
|
||||
const alice: Identity = { kind: 'user', name: 'alice', policies: ['envbao-alice', 'default'] }
|
||||
const bob: Identity = { kind: 'token', name: 'ci', policies: ['envbao-alice', 'ghost'] }
|
||||
const policies = [
|
||||
{ name: 'envbao-alice', hcl: 'path "secret/data/app/*" { capabilities = ["read"] }' },
|
||||
{ name: 'default', hcl: 'path "auth/token/lookup-self" { capabilities = ["read"] }' },
|
||||
{ name: 'legacy', hcl: 'path "secret/data/legacy" { capabilities = ["read"] }' },
|
||||
]
|
||||
|
||||
test('builds identity -> policy -> path nodes and edges', () => {
|
||||
const g = buildAccessGraph([alice], policies)
|
||||
expect(g.nodes.map((n) => n.id)).toEqual(
|
||||
expect.arrayContaining([
|
||||
'identity:user:alice',
|
||||
'policy:envbao-alice',
|
||||
'path:secret/data/app/*',
|
||||
'policy:default',
|
||||
'path:auth/token/lookup-self',
|
||||
]),
|
||||
)
|
||||
expect(g.edges.find((e) => e.id === 'identity:user:alice->policy:envbao-alice')).toBeDefined()
|
||||
expect(g.edges.find((e) => e.id === 'policy:envbao-alice->path:secret/data/app/*')?.capabilities).toEqual(['read'])
|
||||
})
|
||||
|
||||
test('shared policy yields a single node, with an edge per identity', () => {
|
||||
const g = buildAccessGraph([alice, bob], policies)
|
||||
expect(g.nodes.filter((n) => n.id === 'policy:envbao-alice')).toHaveLength(1)
|
||||
expect(g.edges.filter((e) => e.target === 'policy:envbao-alice')).toHaveLength(2)
|
||||
})
|
||||
|
||||
test('marks managed vs unmanaged and missing policies', () => {
|
||||
const g = buildAccessGraph([alice, bob], policies)
|
||||
const get = (n: string) => g.nodes.find((x) => x.id === `policy:${n}`)
|
||||
expect(get('envbao-alice')).toMatchObject({ managed: true, missing: false })
|
||||
expect(get('legacy')).toMatchObject({ managed: false, missing: false })
|
||||
expect(get('ghost')).toMatchObject({ managed: false, missing: true })
|
||||
})
|
||||
|
||||
test('includes policies not attached to any identity', () => {
|
||||
const g = buildAccessGraph([], policies)
|
||||
expect(g.nodes.some((n) => n.id === 'policy:legacy')).toBe(true)
|
||||
expect(g.edges.some((e) => e.source === 'policy:legacy')).toBe(true)
|
||||
})
|
||||
|
||||
test('merges duplicate paths within one policy', () => {
|
||||
const g = buildAccessGraph(
|
||||
[],
|
||||
[{ name: 'p', hcl: 'path "a" { capabilities = ["read"] }\npath "a" { capabilities = ["list"] }' }],
|
||||
)
|
||||
expect(g.edges.find((e) => e.target === 'path:a')?.capabilities).toEqual(['read', 'list'])
|
||||
})
|
||||
|
||||
test('surfaces rule warnings on the policy node', () => {
|
||||
const g = buildAccessGraph([], [{ name: 'p', hcl: 'path "a/{{x}}" { capabilities = ["read"] }' }])
|
||||
expect((g.nodes.find((n) => n.id === 'policy:p') as { warnings: string[] }).warnings[0]).toMatch(/Templated/)
|
||||
})
|
||||
|
||||
test('root policy is unrestricted', () => {
|
||||
const g = buildAccessGraph([{ kind: 'token', name: 'r', policies: ['root'] }], [])
|
||||
expect(g.edges.find((e) => e.target === 'path:*')?.capabilities).toContain('sudo')
|
||||
})
|
||||
|
||||
test('unparseable policy gives warnings and no paths', () => {
|
||||
const g = buildAccessGraph([], [{ name: 'bad', hcl: 'path {' }])
|
||||
expect(g.edges).toEqual([])
|
||||
expect((g.nodes[0] as { warnings: string[] }).warnings[0]).toMatch(/Could not parse/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accessForPath', () => {
|
||||
const policies = [
|
||||
{ name: 'rw', hcl: 'path "secret/data/app/*" { capabilities = ["read", "update"] }' },
|
||||
{ name: 'ro', hcl: 'path "secret/data/app/db" { capabilities = ["read"] }' },
|
||||
{ name: 'no', hcl: 'path "secret/data/app/db" { capabilities = ["deny"] }' },
|
||||
]
|
||||
const ids: Identity[] = [
|
||||
{ kind: 'user', name: 'a', policies: ['rw', 'ro'] },
|
||||
{ kind: 'user', name: 'b', policies: ['rw', 'no'] },
|
||||
{ kind: 'user', name: 'c', policies: ['ro'] },
|
||||
]
|
||||
|
||||
test('lists identities with access, honouring deny', () => {
|
||||
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'])
|
||||
})
|
||||
|
||||
test('returns nothing for unrelated paths', () => {
|
||||
expect(accessForPath(ids, policies, 'secret/data/other', pathMatches)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
import { HclSyntaxError, parseHcl, type HclValue } from './hcl'
|
||||
|
||||
export const CAPABILITIES = ['create', 'read', 'update', 'patch', 'delete', 'list', 'sudo', 'deny'] as const
|
||||
export type Capability = (typeof CAPABILITIES)[number]
|
||||
|
||||
export interface PolicyRule {
|
||||
path: string
|
||||
capabilities: Capability[]
|
||||
/** Constructs we cannot model precisely (parameter constraints, templating, ...). */
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export interface ParsedPolicy {
|
||||
rules: PolicyRule[]
|
||||
/** Policy-level problems: syntax errors, unknown blocks. */
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
// Attributes on a path block that restrict or modify access beyond capabilities.
|
||||
const CONSTRAINT_ATTRS = [
|
||||
'allowed_parameters',
|
||||
'denied_parameters',
|
||||
'required_parameters',
|
||||
'min_wrapping_ttl',
|
||||
'max_wrapping_ttl',
|
||||
'control_group',
|
||||
'mfa_methods',
|
||||
]
|
||||
|
||||
const isCapability = (c: HclValue): c is Capability => CAPABILITIES.includes(c as Capability)
|
||||
|
||||
export function parsePolicy(hcl: string): ParsedPolicy {
|
||||
let body
|
||||
try {
|
||||
body = parseHcl(hcl)
|
||||
} catch (e) {
|
||||
if (e instanceof HclSyntaxError) return { rules: [], warnings: [`Could not parse policy: ${e.message}`] }
|
||||
throw e
|
||||
}
|
||||
|
||||
const warnings: string[] = []
|
||||
const rules: PolicyRule[] = []
|
||||
|
||||
for (const [name] of Object.entries(body.attributes)) warnings.push(`Ignored top-level attribute "${name}"`)
|
||||
|
||||
for (const block of body.blocks) {
|
||||
if (block.type !== 'path' || block.labels.length !== 1) {
|
||||
warnings.push(`Ignored unsupported block "${block.type}"`)
|
||||
continue
|
||||
}
|
||||
const path = block.labels[0]
|
||||
const ruleWarnings: string[] = []
|
||||
|
||||
const caps = block.body.attributes.capabilities
|
||||
const capabilities: Capability[] = []
|
||||
if (!Array.isArray(caps)) {
|
||||
ruleWarnings.push('No capabilities list')
|
||||
} else {
|
||||
for (const c of caps) {
|
||||
if (isCapability(c)) {
|
||||
if (!capabilities.includes(c)) capabilities.push(c)
|
||||
} else ruleWarnings.push(`Unknown capability "${String(c)}"`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const attr of CONSTRAINT_ATTRS) {
|
||||
if (attr in block.body.attributes || block.body.blocks.some((b) => b.type === attr)) {
|
||||
ruleWarnings.push(`Constraint "${attr}" is not reflected in the graph`)
|
||||
}
|
||||
}
|
||||
if (path.includes('{{')) ruleWarnings.push('Templated path is approximated')
|
||||
|
||||
rules.push({ path, capabilities, warnings: ruleWarnings })
|
||||
}
|
||||
|
||||
return { rules, warnings }
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a policy rule path cover a concrete path?
|
||||
* `+` matches exactly one segment; a trailing `*` matches any suffix (including none).
|
||||
* Templated segments (`{{...}}`) are treated as `+`.
|
||||
*/
|
||||
export function pathMatches(rulePath: string, target: string): boolean {
|
||||
const prefixGlob = rulePath.endsWith('*')
|
||||
const pattern = prefixGlob ? rulePath.slice(0, -1) : rulePath
|
||||
const pSegs = pattern.split('/')
|
||||
const tSegs = target.split('/')
|
||||
|
||||
if (!prefixGlob) {
|
||||
if (pSegs.length !== tSegs.length) return false
|
||||
return pSegs.every((p, i) => segmentMatches(p, tSegs[i]))
|
||||
}
|
||||
|
||||
// Everything before the final (partial) segment must match whole segments;
|
||||
// the last pattern segment is a literal prefix of the corresponding target segment.
|
||||
const last = pSegs.length - 1
|
||||
if (tSegs.length < pSegs.length) return false
|
||||
for (let i = 0; i < last; i++) if (!segmentMatches(pSegs[i], tSegs[i])) return false
|
||||
const lastPat = pSegs[last]
|
||||
if (lastPat.includes('+') || lastPat.includes('{{')) return segmentMatches(lastPat, tSegs[last]) || tSegs.length > pSegs.length
|
||||
return tSegs[last].startsWith(lastPat)
|
||||
}
|
||||
|
||||
function segmentMatches(pattern: string, segment: string): boolean {
|
||||
if (pattern === '+' || /^\{\{.*\}\}$/.test(pattern)) return segment.length > 0
|
||||
return pattern === segment
|
||||
}
|
||||
|
||||
/** Effective capabilities of a set of rules on a concrete path; `deny` wins. */
|
||||
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))
|
||||
}
|
||||
return caps.has('deny') ? ['deny'] : [...caps]
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"types": ["vite/client", "node"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
|
||||
Reference in new issue
Block a user