Add grant/revoke flow with managed per-identity policies
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cd1438987b
commit
5180e1bb74
11 files changed
+720
-1
No files matched your search
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import {
|
||||
kvGrantRules,
|
||||
managedPolicyName,
|
||||
parseManagedPolicy,
|
||||
removeGrant,
|
||||
renderManagedPolicy,
|
||||
upsertGrant,
|
||||
validateGrantPath,
|
||||
} from './managed'
|
||||
import { parsePolicy } from './policy'
|
||||
|
||||
describe('managedPolicyName', () => {
|
||||
test.each([
|
||||
['user', 'alice', 'envbao-user-alice'],
|
||||
['group', 'Dev Team', 'envbao-group-dev-team'],
|
||||
['entity', 'a@b.c', 'envbao-entity-a-b.c'],
|
||||
] as const)('%s %s', (kind, name, expected) => expect(managedPolicyName(kind, name)).toBe(expected))
|
||||
})
|
||||
|
||||
describe('validateGrantPath', () => {
|
||||
test.each(['', ' a', '/a', 'a"b', 'a\\b', 'a*/b'])('rejects %j', (p) => expect(validateGrantPath(p)).not.toBeNull())
|
||||
test.each(['secret/data/app', 'secret/data/app/*', 'secret/data/+/x', 'secret/data/app*'])('accepts %s', (p) =>
|
||||
expect(validateGrantPath(p)).toBeNull(),
|
||||
)
|
||||
})
|
||||
|
||||
describe('render / parse round trip', () => {
|
||||
const grants = [
|
||||
{ path: 'secret/data/b/*', capabilities: ['update', 'read'] as const },
|
||||
{ path: 'secret/data/a', capabilities: ['read'] as const },
|
||||
].map((g) => ({ path: g.path, capabilities: [...g.capabilities] }))
|
||||
|
||||
test('rendered policy is valid HCL for the policy parser, sorted, with canonical capability order', () => {
|
||||
const hcl = renderManagedPolicy('user', 'alice', grants)
|
||||
expect(parsePolicy(hcl).warnings).toEqual([])
|
||||
expect(parsePolicy(hcl).rules.map((r) => r.path)).toEqual(['secret/data/a', 'secret/data/b/*'])
|
||||
expect(hcl).toContain('capabilities = ["read", "update"]')
|
||||
})
|
||||
|
||||
test('parse recovers owner and grants and is editable', () => {
|
||||
const m = parseManagedPolicy(renderManagedPolicy('group', 'devs', grants))
|
||||
expect(m.owner).toBe('group:devs')
|
||||
expect(m.editable).toBe(true)
|
||||
expect(m.grants.map((g) => g.path)).toEqual(['secret/data/a', 'secret/data/b/*'])
|
||||
})
|
||||
|
||||
test('an empty policy is still valid and editable', () => {
|
||||
expect(parseManagedPolicy(renderManagedPolicy('user', 'x', [])).editable).toBe(true)
|
||||
})
|
||||
|
||||
test('hand-edited constraints make it non-editable', () => {
|
||||
const hcl = `# envbao-owner: user:alice\npath "a" {\n capabilities = ["read"]\n allowed_parameters = { "x" = [] }\n}`
|
||||
const m = parseManagedPolicy(hcl)
|
||||
expect(m.editable).toBe(false)
|
||||
expect(m.reasons.join()).toMatch(/allowed_parameters/)
|
||||
})
|
||||
|
||||
test('policies without our marker are not editable', () => {
|
||||
const m = parseManagedPolicy('path "a" { capabilities = ["read"] }')
|
||||
expect(m.owner).toBeNull()
|
||||
expect(m.editable).toBe(false)
|
||||
})
|
||||
|
||||
test('duplicate paths are not editable', () => {
|
||||
const hcl = `# envbao-owner: user:a\npath "a" { capabilities = ["read"] }\npath "a" { capabilities = ["list"] }`
|
||||
expect(parseManagedPolicy(hcl).editable).toBe(false)
|
||||
})
|
||||
|
||||
test('unparseable policy is not editable', () => {
|
||||
expect(parseManagedPolicy('# envbao-owner: user:a\npath "a" {').editable).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('upsertGrant / removeGrant', () => {
|
||||
const g = [{ path: 'a', capabilities: ['read' as const] }]
|
||||
test('replaces capabilities for an existing path', () => {
|
||||
expect(upsertGrant(g, { path: 'a', capabilities: ['update'] })).toEqual([{ path: 'a', capabilities: ['update'] }])
|
||||
})
|
||||
test('adds new paths', () => expect(upsertGrant(g, { path: 'b', capabilities: ['read'] })).toHaveLength(2))
|
||||
test('empty capabilities remove the path', () => expect(upsertGrant(g, { path: 'a', capabilities: [] })).toEqual([]))
|
||||
test('removeGrant', () => expect(removeGrant(g, 'a')).toEqual([]))
|
||||
})
|
||||
|
||||
describe('kvGrantRules', () => {
|
||||
test('splits data operations and list into data/ and metadata/ rules', () => {
|
||||
expect(kvGrantRules('secret/', 'app/*', ['read', 'update', 'list'])).toEqual([
|
||||
{ path: 'secret/data/app/*', capabilities: ['read', 'update'] },
|
||||
{ path: 'secret/metadata/app/*', capabilities: ['list'] },
|
||||
])
|
||||
})
|
||||
test('no list means an empty metadata rule (to be dropped by upsert)', () => {
|
||||
expect(kvGrantRules('secret', 'x', ['read'])[1]).toEqual({ path: 'secret/metadata/x', capabilities: [] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { MANAGED_PREFIX } from './graph'
|
||||
import { CAPABILITIES, parsePolicy, type Capability } from './policy'
|
||||
|
||||
/** Identity kinds that can hold a managed policy. Tokens cannot: their policies are fixed at creation. */
|
||||
export type GrantTarget = 'user' | 'entity' | 'group'
|
||||
|
||||
export interface Grant {
|
||||
/** Full API path, e.g. "secret/data/app/*". */
|
||||
path: string
|
||||
capabilities: Capability[]
|
||||
}
|
||||
|
||||
export interface ManagedPolicy {
|
||||
owner: string | null
|
||||
grants: Grant[]
|
||||
/** False when the policy has anything the form cannot round-trip (or isn't ours). */
|
||||
editable: boolean
|
||||
reasons: string[]
|
||||
}
|
||||
|
||||
const OWNER_RE = /^# envbao-owner: (user|entity|group):(.+)$/m
|
||||
|
||||
export const ownerTag = (kind: GrantTarget, name: string) => `${kind}:${name}`
|
||||
|
||||
/** OpenBao lowercases policy names; keep to a safe character set. */
|
||||
export function managedPolicyName(kind: GrantTarget, name: string): string {
|
||||
const safe = name.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-')
|
||||
return `${MANAGED_PREFIX}${kind}-${safe}`
|
||||
}
|
||||
|
||||
/** Returns an error message, or null if the path can be written safely into a policy. */
|
||||
export function validateGrantPath(path: string): string | null {
|
||||
if (!path.trim()) return 'Path is required.'
|
||||
if (path !== path.trim()) return 'Path must not start or end with spaces.'
|
||||
if (path.startsWith('/')) return 'Path must not start with "/".'
|
||||
if (/["\\\n\r]/.test(path)) return 'Path must not contain quotes, backslashes or line breaks.'
|
||||
if (path.includes('*') && !path.endsWith('*')) return '"*" is only allowed at the end of a path.'
|
||||
return null
|
||||
}
|
||||
|
||||
export function renderManagedPolicy(kind: GrantTarget, name: string, grants: Grant[]): string {
|
||||
const sorted = [...grants].sort((a, b) => a.path.localeCompare(b.path))
|
||||
const header = [
|
||||
'# Managed by EnvBao. Changes made outside EnvBao may be overwritten.',
|
||||
`# envbao-owner: ${ownerTag(kind, name)}`,
|
||||
]
|
||||
const blocks = sorted.map((g) => {
|
||||
const caps = CAPABILITIES.filter((c) => g.capabilities.includes(c))
|
||||
return `path "${g.path}" {\n capabilities = [${caps.map((c) => `"${c}"`).join(', ')}]\n}`
|
||||
})
|
||||
return [...header, '', ...blocks].join('\n') + '\n'
|
||||
}
|
||||
|
||||
export function parseManagedPolicy(hcl: string): ManagedPolicy {
|
||||
const owner = OWNER_RE.exec(hcl)?.[0].replace('# envbao-owner: ', '') ?? null
|
||||
const parsed = parsePolicy(hcl)
|
||||
const reasons: string[] = []
|
||||
if (!owner) reasons.push('Not created by EnvBao (no owner marker).')
|
||||
reasons.push(...parsed.warnings)
|
||||
for (const r of parsed.rules) reasons.push(...r.warnings.map((w) => `${r.path}: ${w}`))
|
||||
const seen = new Set<string>()
|
||||
for (const r of parsed.rules) {
|
||||
if (seen.has(r.path)) reasons.push(`${r.path}: declared more than once`)
|
||||
seen.add(r.path)
|
||||
}
|
||||
return {
|
||||
owner,
|
||||
grants: parsed.rules.map((r) => ({ path: r.path, capabilities: r.capabilities })),
|
||||
editable: reasons.length === 0,
|
||||
reasons,
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace the grant for `grant.path`; an empty capability list removes it. */
|
||||
export function upsertGrant(grants: Grant[], grant: Grant): Grant[] {
|
||||
const rest = grants.filter((g) => g.path !== grant.path)
|
||||
return grant.capabilities.length ? [...rest, grant] : rest
|
||||
}
|
||||
|
||||
export const removeGrant = (grants: Grant[], path: string): Grant[] => grants.filter((g) => g.path !== path)
|
||||
|
||||
export type KvCapability = 'read' | 'create' | 'update' | 'delete' | 'list'
|
||||
export const KV_CAPABILITIES: KvCapability[] = ['read', 'create', 'update', 'delete', 'list']
|
||||
|
||||
/**
|
||||
* Expand a KV v2 grant on `mount` + `secretPath` into API-path rules: data operations apply to
|
||||
* `<mount>data/<path>`, while `list` is a metadata operation on `<mount>metadata/<path>`.
|
||||
*/
|
||||
export function kvGrantRules(mount: string, secretPath: string, caps: KvCapability[]): Grant[] {
|
||||
const m = mount.endsWith('/') ? mount : `${mount}/`
|
||||
const dataCaps = caps.filter((c): c is Exclude<KvCapability, 'list'> => c !== 'list')
|
||||
return [
|
||||
{ path: `${m}data/${secretPath}`, capabilities: dataCaps },
|
||||
{ path: `${m}metadata/${secretPath}`, capabilities: caps.includes('list') ? ['list'] : [] },
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user