diff --git a/src/api/engines/registry.ts b/src/api/engines/registry.ts index e4e1f13..3631700 100644 --- a/src/api/engines/registry.ts +++ b/src/api/engines/registry.ts @@ -1,3 +1,4 @@ +import type { Capability } from '../../model/policy' import type { Mount } from '../secrets' import { isKvV2 } from '../secrets' @@ -37,6 +38,8 @@ export interface CredKind { method: 'GET' | 'POST' /** Request parameters; only sent for POST. */ inputs: FieldDef[] + /** ACL capabilities a token needs on `path` to make this request (and so what "generate" grants). */ + capabilities: Capability[] } /** A one-off call on a config, e.g. rotating the root credentials. */ @@ -107,7 +110,7 @@ const DATABASE_ROLE: RoleKind = { { key: 'default_ttl', label: 'Default TTL', type: 'ttl' }, { key: 'max_ttl', label: 'Max TTL', type: 'ttl' }, ], - creds: [{ id: 'creds', label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [] }], + creds: [{ id: 'creds', label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] }], } const DATABASE_STATIC_ROLE: RoleKind = { @@ -121,7 +124,7 @@ const DATABASE_STATIC_ROLE: RoleKind = { { key: 'rotation_period', label: 'Rotation period', type: 'ttl' }, ], creds: [ - { id: 'static-creds', label: 'Read current credentials', path: (r) => `static-creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [] }, + { id: 'static-creds', label: 'Read current credentials', path: (r) => `static-creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] }, ], } @@ -152,6 +155,7 @@ const AWS_ROLE: RoleKind = { label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'POST', + capabilities: ['read', 'update'], inputs: [ { key: 'ttl', label: 'TTL', type: 'ttl', help: 'For STS credentials.' }, { key: 'role_arn', label: 'Role ARN', type: 'text', help: 'Only when the role allows several.' }, @@ -181,6 +185,7 @@ const SSH_ROLE: RoleKind = { label: 'Sign a public key (CA)', path: (r) => `sign/${encodeURIComponent(r)}`, method: 'POST', + capabilities: ['update'], inputs: [ { key: 'public_key', label: 'Public key', type: 'textarea', required: true }, { key: 'valid_principals', label: 'Valid principals', type: 'text', help: 'Comma separated.' }, @@ -193,6 +198,7 @@ const SSH_ROLE: RoleKind = { label: 'Generate an OTP', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'POST', + capabilities: ['update'], inputs: [ { key: 'ip', label: 'Target IP', type: 'text', required: true }, { key: 'username', label: 'Username', type: 'text' }, diff --git a/src/api/engines/roles.integration.test.ts b/src/api/engines/roles.integration.test.ts index 75d85ea..74b4924 100644 --- a/src/api/engines/roles.integration.test.ts +++ b/src/api/engines/roles.integration.test.ts @@ -3,7 +3,11 @@ import { BaoClient } from '../bao' import { readConfig, runAction, writeConfig, deleteConfig } from './config' import { generateCreds } from './creds' import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases' -import { listMounts } from '../secrets' +import { accessForPath } from '../../model/graph' +import { dynamicGrantRules, renderManagedPolicy } from '../../model/managed' +import { pathMatches } from '../../model/policy' +import { capabilitiesSelf, listMounts } from '../secrets' +import { createToken, revokeToken } from '../tokens' import { ENGINES } from './registry' import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles' @@ -126,3 +130,48 @@ describe('dynamic engine config and credentials', () => { expect(await readConfig(client, awsMount, lease)).toMatchObject({ lease: '30m0s', lease_max: '2h0m0s' }) }) }) + +describe('grants on dynamic roles match what OpenBao enforces', () => { + const polName = `it-dyn-${sfx}` + const ca = ENGINES.ssh.configs[0] + let token: Awaited> + + beforeAll(async () => { + const role = emptyDraft(kind) + role.values.allow_user_certificates = true + role.values.allowed_users = '*' + role.values.default_user = 'alice' + for (const name of ['granted', 'other']) await writeRole(client, mount, kind, name, payloadFromDraft(kind, role)) + await runAction(client, mount, ca.actions![0]) + + const grants = dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length) + await client.request('PUT', `sys/policies/acl/${polName}`, { policy: renderManagedPolicy('user', 'x', grants) }) + token = await createToken(client, { displayName: polName, policies: [polName], renewable: false, orphan: false }) + }) + + afterAll(async () => { + await revokeToken(client, token.accessor).catch(() => {}) + await client.request('DELETE', `sys/policies/acl/${polName}`).catch(() => {}) + }) + + test('capabilities-self agrees with the access model for granted and other roles', async () => { + const as = client.withToken(token.token) + const hcl = renderManagedPolicy('user', 'x', dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length)) + const who = [{ kind: 'user' as const, name: 'x', policies: [polName] }] + for (const role of ['granted', 'other']) { + for (const path of [`${mount}sign/${role}`, `${mount}creds/${role}`, `${mount}roles/${role}`]) { + const real = (await capabilitiesSelf(as, path)).filter((c) => c !== 'deny').sort() + const modelled = accessForPath(who, [{ name: polName, hcl }], path, pathMatches).flatMap((e) => e.capabilities).sort() + expect(modelled, path).toEqual(real) + } + } + }) + + test('the granted token can sign with its role and not with another', async () => { + const as = client.withToken(token.token) + const out = await generateCreds(as, mount, kind.creds[0], 'granted', { public_key: PUBLIC_KEY }) + expect(String(out.data.signed_key)).toContain('cert-v01') + await expect(generateCreds(as, mount, kind.creds[0], 'other', { public_key: PUBLIC_KEY })).rejects.toThrow() + expect(await listRoles(as, mount, kind)).toEqual(expect.arrayContaining(['granted'])) + }) +}) diff --git a/src/features/access/AccessEditor.test.tsx b/src/features/access/AccessEditor.test.tsx index 55076dd..f6e2567 100644 --- a/src/features/access/AccessEditor.test.tsx +++ b/src/features/access/AccessEditor.test.tsx @@ -4,11 +4,18 @@ import userEvent from '@testing-library/user-event' import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { BaoClient } from '../../api/bao' import * as grants from '../../api/grants' +import * as roles from '../../api/engines/roles' import * as secrets from '../../api/secrets' import { AccessEditor } from './AccessEditor' vi.mock('../../api/grants') -vi.mock('../../api/secrets') +vi.mock('../../api/engines/roles') +vi.mock('../../api/secrets', async (orig) => ({ + ...(await orig()), + listMounts: vi.fn(), + listSecrets: vi.fn(), + readPolicyHcl: vi.fn(), +})) const client = new BaoClient('http://b', 't') const target = { kind: 'user' as const, name: 'alice' } @@ -29,7 +36,7 @@ const state = (over: Partial = {}): grants.GrantState => ({ beforeEach(() => { vi.mocked(grants.getGrantState).mockResolvedValue(state()) - vi.mocked(secrets.listKvMounts).mockResolvedValue([{ path: 'secret/' }]) + vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }]) vi.mocked(secrets.listSecrets).mockImplementation(async (_c, _m, prefix) => prefix === '' ? [ @@ -140,3 +147,32 @@ test('shows load errors', async () => { setup() expect(await screen.findByRole('alert')).toHaveTextContent('permission denied') }) + +test('grants generate on a dynamic-engine role from the identity side', async () => { + vi.mocked(secrets.listMounts).mockResolvedValue([ + { path: 'secret/', type: 'kv', version: '2' }, + { path: 'database/', type: 'database' }, + ]) + vi.mocked(roles.listRoles).mockResolvedValue(['readonly', 'readwrite']) + vi.mocked(grants.grantAccess).mockResolvedValue() + const user = setup() + await user.selectOptions(await screen.findByLabelText('Secrets engine'), 'database/') + await user.click(await screen.findByLabelText('readwrite')) + await user.click(screen.getByLabelText(/Manage role/)) + await user.click(screen.getByRole('button', { name: 'Grant' })) + expect(grants.grantAccess).toHaveBeenCalledWith(client, target, [ + { path: 'database/creds/readwrite', capabilities: ['read'] }, + { path: 'database/roles/readwrite', capabilities: ['create', 'read', 'update', 'delete'] }, + { path: 'database/roles', capabilities: ['list'] }, + ]) +}) + +test('a dynamic grant needs a role chosen', async () => { + vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'database/', type: 'database' }]) + vi.mocked(roles.listRoles).mockResolvedValue(['readonly']) + const user = setup() + await screen.findByLabelText('readonly') + await user.click(screen.getByRole('button', { name: 'Grant' })) + expect(await screen.findByRole('alert')).toHaveTextContent('Choose a role.') + expect(grants.grantAccess).not.toHaveBeenCalled() +}) diff --git a/src/features/access/AccessEditor.tsx b/src/features/access/AccessEditor.tsx index 3e3104e..0a8beeb 100644 --- a/src/features/access/AccessEditor.tsx +++ b/src/features/access/AccessEditor.tsx @@ -2,13 +2,17 @@ import { useMutation, useQuery } from '@tanstack/react-query' import { useState, type FormEvent } from 'react' import type { BaoClient } from '../../api/bao' import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants' -import { listKvMounts, readPolicyHcl } from '../../api/secrets' -import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed' +import { engineFor, mountKind } from '../../api/engines/registry' +import { readPolicyHcl } from '../../api/secrets' +import { dynamicGrantRules, kvGrantRules, validateGrantPath, type DynamicAccess, type KvCapability } from '../../model/managed' import { groupGrants } from '../../model/grantRows' import { CapabilityChips } from '../shared/CapabilityChips' import { CapabilityPicker } from '../shared/CapabilityPicker' +import { DynamicAccessPicker } from '../shared/DynamicAccessPicker' +import { useMounts } from '../shared/useMounts' import { useRefreshAccess } from '../shared/useRefreshAccess' import { PathPicker } from './PathPicker' +import { RolePicker, type RoleSelection } from './RolePicker' import { useConfirm } from '../shared/useConfirm' interface Props { @@ -35,21 +39,29 @@ export function AccessEditor({ client, target, onClose }: Props) { const confirm = useConfirm() const stateKey = ['grant-state', target.kind, target.name] const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) }) - const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) }) + const mounts = useMounts(client) const [mountChoice, setMount] = useState(null) const [secretPath, setSecretPath] = useState('') const [caps, setCaps] = useState(['read']) + const [roleSel, setRoleSel] = useState({ kindId: '', role: '' }) + const [access, setAccess] = useState(['generate']) const [showRaw, setShowRaw] = useState(false) const [formError, setFormError] = useState(null) - const mount = mountChoice ?? mounts.data?.[0]?.path ?? '' + const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0] + const mount = current?.path ?? '' + const dynamic = current !== undefined && mountKind(current) === 'dynamic' + const engine = dynamic ? engineFor(current.type) : null + const roleKind = engine ? (engine.roleKinds.find((k) => k.id === roleSel.kindId) ?? engine.roleKinds[0]) : null const done = useRefreshAccess() const grant = useMutation({ - mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)), + mutationFn: () => + grantAccess(client, target, roleKind ? dynamicGrantRules(roleKind, mount, roleSel.role, access) : kvGrantRules(mount, secretPath, caps)), onSuccess: () => { setSecretPath('') + setRoleSel({ kindId: roleSel.kindId, role: '' }) return done() }, }) @@ -57,7 +69,10 @@ export function AccessEditor({ client, target, onClose }: Props) { function submit(e: FormEvent) { e.preventDefault() - const err = validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null) + const err = roleKind + ? (roleSel.role ? validateGrantPath(`${mount}${roleKind.path}/${roleSel.role}`) : 'Choose a role.') ?? + (access.length === 0 ? 'Select at least one kind of access.' : null) + : (validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null)) setFormError(err) if (!err) grant.mutate() } @@ -163,6 +178,7 @@ export function AccessEditor({ client, target, onClose }: Props) { onChange={(e) => { setMount(e.target.value) setSecretPath('') + setRoleSel({ kindId: '', role: '' }) }} > {mounts.data?.map((m) => ( @@ -170,10 +186,13 @@ export function AccessEditor({ client, target, onClose }: Props) { ))} - {mount && } - + {mount && engine && } + {mount && !engine && } + {engine ? : }

- Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path. + {engine + ? 'Granting a role that already has a grant replaces its access. Unticked access is removed.' + : 'Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.'}

{(formError || grant.error) &&

{formError ?? grant.error?.message}

}