From 4fa7ff1497a5ee726e652323a5566c7d678e9c64 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Mon, 9 Nov 2026 13:24:50 +0000 Subject: [PATCH] Secrets: manage roles for database, aws, ssh and generic engines Registry gains per-engine role kinds with field schemas (database dynamic and static roles, aws, ssh); unknown engines get a raw JSON role editor. RolesPanel lists, creates, edits and deletes roles, and edits write back fields the form does not know about so they are not dropped. Covered by unit tests and an ssh integration test. Co-Authored-By: Claude Sonnet 5.5 --- src/api/engines/registry.ts | 119 ++++++++++++++++-- src/api/engines/roles.integration.test.ts | 49 ++++++++ src/api/engines/roles.test.ts | 101 +++++++++++++++ src/api/engines/roles.ts | 105 ++++++++++++++++ src/features/secrets/EngineView.tsx | 15 ++- src/features/secrets/RoleEditor.tsx | 121 ++++++++++++++++++ src/features/secrets/RolesPanel.test.tsx | 123 ++++++++++++++++++ src/features/secrets/RolesPanel.tsx | 144 ++++++++++++++++++++++ src/features/secrets/SecretsPage.test.tsx | 4 +- src/features/secrets/SecretsPage.tsx | 2 +- 10 files changed, 769 insertions(+), 14 deletions(-) create mode 100644 src/api/engines/roles.integration.test.ts create mode 100644 src/api/engines/roles.test.ts create mode 100644 src/api/engines/roles.ts create mode 100644 src/features/secrets/RoleEditor.tsx create mode 100644 src/features/secrets/RolesPanel.test.tsx create mode 100644 src/features/secrets/RolesPanel.tsx diff --git a/src/api/engines/registry.ts b/src/api/engines/registry.ts index 5a663c5..2eee0ce 100644 --- a/src/api/engines/registry.ts +++ b/src/api/engines/registry.ts @@ -1,19 +1,124 @@ import type { Mount } from '../secrets' import { isKvV2 } from '../secrets' -/** Describes a dynamic secrets engine the UI can manage. Grows in later phases (role fields, creds, config). */ +export type FieldType = + /** Single-line string. */ + | 'text' + /** Multi-line string sent as-is (e.g. a JSON policy document). */ + | 'textarea' + /** Duration such as "1h" or "3600s"; read back from OpenBao as seconds. */ + | 'ttl' + /** Comma or newline separated values sent as a string array. */ + | 'list' + /** Statements separated by blank lines (SQL can contain commas) sent as a string array. */ + | 'statements' + | 'bool' + | 'select' + +export interface FieldDef { + key: string + label: string + type: FieldType + required?: boolean + options?: string[] + help?: string +} + +/** One family of roles under a mount, e.g. database "roles" and "static-roles". */ +export interface RoleKind { + id: string + label: string + /** Path relative to the mount that roles are listed and written under. */ + path: string + /** Empty means the role is edited as raw JSON (generic engines). */ + fields: FieldDef[] +} + +/** Describes a dynamic secrets engine the UI can manage. Grows in later phases (creds, config). */ export interface EngineDef { /** Engine type as reported by sys/mounts. */ type: string label: string - /** Path, relative to the mount, that roles are listed/written under. */ - rolesPath: string + roleKinds: RoleKind[] +} + +const DATABASE_ROLE: RoleKind = { + id: 'roles', + label: 'Dynamic roles', + path: 'roles', + fields: [ + { key: 'db_name', label: 'Database config name', type: 'text', required: true }, + { + key: 'creation_statements', + label: 'Creation statements', + type: 'statements', + required: true, + help: 'Separate statements with a blank line. Use {{name}}, {{password}} and {{expiration}}.', + }, + { key: 'revocation_statements', label: 'Revocation statements', type: 'statements' }, + { key: 'renew_statements', label: 'Renew statements', type: 'statements' }, + { key: 'rollback_statements', label: 'Rollback statements', type: 'statements' }, + { key: 'default_ttl', label: 'Default TTL', type: 'ttl' }, + { key: 'max_ttl', label: 'Max TTL', type: 'ttl' }, + ], +} + +const DATABASE_STATIC_ROLE: RoleKind = { + id: 'static-roles', + label: 'Static roles', + path: 'static-roles', + fields: [ + { key: 'db_name', label: 'Database config name', type: 'text', required: true }, + { key: 'username', label: 'Database username', type: 'text', required: true }, + { key: 'rotation_statements', label: 'Rotation statements', type: 'statements' }, + { key: 'rotation_period', label: 'Rotation period', type: 'ttl' }, + ], +} + +const AWS_ROLE: RoleKind = { + id: 'roles', + label: 'Roles', + path: 'roles', + fields: [ + { + key: 'credential_type', + label: 'Credential type', + type: 'select', + required: true, + options: ['iam_user', 'assumed_role', 'federation_token'], + }, + { key: 'role_arns', label: 'Role ARNs', type: 'list', help: 'For assumed_role.' }, + { key: 'policy_arns', label: 'Policy ARNs', type: 'list' }, + { key: 'policy_document', label: 'Policy document (JSON)', type: 'textarea' }, + { key: 'iam_groups', label: 'IAM groups', type: 'list', help: 'For iam_user.' }, + { key: 'default_sts_ttl', label: 'Default STS TTL', type: 'ttl' }, + { key: 'max_sts_ttl', label: 'Max STS TTL', type: 'ttl' }, + { key: 'permissions_boundary_arn', label: 'Permissions boundary ARN', type: 'text' }, + { key: 'user_path', label: 'IAM user path', type: 'text' }, + ], +} + +const SSH_ROLE: RoleKind = { + id: 'roles', + label: 'Roles', + path: 'roles', + fields: [ + { key: 'key_type', label: 'Key type', type: 'select', required: true, options: ['ca', 'otp'] }, + { key: 'default_user', label: 'Default user', type: 'text' }, + { key: 'allowed_users', label: 'Allowed users', type: 'text', help: 'Comma separated; * allows any.' }, + { key: 'cidr_list', label: 'CIDR list', type: 'text', help: 'otp only. Comma separated.' }, + { key: 'ttl', label: 'TTL', type: 'ttl' }, + { key: 'max_ttl', label: 'Max TTL', type: 'ttl' }, + { key: 'allow_user_certificates', label: 'Allow user certificates', type: 'bool' }, + { key: 'allow_host_certificates', label: 'Allow host certificates', type: 'bool' }, + { key: 'allowed_extensions', label: 'Allowed extensions', type: 'text' }, + ], } export const ENGINES: Record = { - database: { type: 'database', label: 'Database', rolesPath: 'roles' }, - aws: { type: 'aws', label: 'AWS', rolesPath: 'roles' }, - ssh: { type: 'ssh', label: 'SSH', rolesPath: 'roles' }, + database: { type: 'database', label: 'Database', roleKinds: [DATABASE_ROLE, DATABASE_STATIC_ROLE] }, + aws: { type: 'aws', label: 'AWS', roleKinds: [AWS_ROLE] }, + ssh: { type: 'ssh', label: 'SSH', roleKinds: [SSH_ROLE] }, } /** Engine types that are managed as plain secret stores or by the system, not as dynamic engines. */ @@ -21,7 +126,7 @@ const NOT_DYNAMIC = new Set(['kv', 'generic', 'cubbyhole', 'system', 'identity'] /** Known engine definition, or a generic fallback (raw JSON roles) for any other dynamic engine type. */ export function engineFor(type: string): EngineDef { - return ENGINES[type] ?? { type, label: type, rolesPath: 'roles' } + return ENGINES[type] ?? { type, label: type, roleKinds: [{ id: 'roles', label: 'Roles', path: 'roles', fields: [] }] } } export type MountKind = 'kv' | 'dynamic' diff --git a/src/api/engines/roles.integration.test.ts b/src/api/engines/roles.integration.test.ts new file mode 100644 index 0000000..7c78adb --- /dev/null +++ b/src/api/engines/roles.integration.test.ts @@ -0,0 +1,49 @@ +import { afterAll, beforeAll, describe, expect, test } from 'vitest' +import { BaoClient } from '../bao' +import { listMounts } from '../secrets' +import { ENGINES } from './registry' +import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles' + +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 mount = `it-ssh-${sfx}/` +const kind = ENGINES.ssh.roleKinds[0] + +beforeAll(async () => { + await client.request('POST', `sys/mounts/${mount.slice(0, -1)}`, { type: 'ssh' }) +}) + +afterAll(async () => { + await client.request('DELETE', `sys/mounts/${mount.slice(0, -1)}`).catch(() => {}) +}) + +describe('dynamic engine roles (ssh)', () => { + test('the new mount is listed with its type', async () => { + const m = (await listMounts(client)).find((x) => x.path === mount) + expect(m?.type).toBe('ssh') + }) + + test('creates, lists, edits and deletes a role through the form model', async () => { + expect(await listRoles(client, mount, kind)).toEqual([]) + + const draft = emptyDraft(kind) + draft.values.key_type = 'ca' + draft.values.allowed_users = 'alice,bob' + draft.values.ttl = '30m' + draft.values.allow_user_certificates = true + await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, draft)) + expect(await listRoles(client, mount, kind)).toEqual(['ops']) + + const read = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops')) + expect(read.values).toMatchObject({ key_type: 'ca', allowed_users: 'alice,bob', ttl: '1800s', allow_user_certificates: true }) + + // an edit writes the whole role back, so values it did not touch must survive + read.values.max_ttl = '2h' + await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, read)) + const again = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops')) + expect(again.values).toMatchObject({ allowed_users: 'alice,bob', ttl: '1800s', max_ttl: '7200s' }) + + await deleteRole(client, mount, kind, 'ops') + expect(await listRoles(client, mount, kind)).toEqual([]) + }) +}) diff --git a/src/api/engines/roles.test.ts b/src/api/engines/roles.test.ts new file mode 100644 index 0000000..b969469 --- /dev/null +++ b/src/api/engines/roles.test.ts @@ -0,0 +1,101 @@ +import { expect, test, vi } from 'vitest' +import { BaoClient } from '../bao' +import { ENGINES, engineFor, mountKind } from './registry' +import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles' + +const dbRole = ENGINES.database.roleKinds[0] +const awsRole = ENGINES.aws.roleKinds[0] +const sshRole = ENGINES.ssh.roleKinds[0] + +test('classifies mounts', () => { + expect(mountKind({ path: 'secret/', type: 'kv', version: '2' })).toBe('kv') + expect(mountKind({ path: 'old/', type: 'kv', version: '1' })).toBeNull() + expect(mountKind({ path: 'cubbyhole/', type: 'cubbyhole' })).toBeNull() + expect(mountKind({ path: 'database/', type: 'database' })).toBe('dynamic') + expect(mountKind({ path: 'pki/', type: 'pki' })).toBe('dynamic') +}) + +test('unknown engines fall back to a raw JSON role editor', () => { + const e = engineFor('pki') + expect(e.label).toBe('pki') + expect(e.roleKinds[0].fields).toEqual([]) +}) + +test('database role round-trips through the form, keeping unknown fields', () => { + const data = { + db_name: 'pg', + creation_statements: ['CREATE ROLE "{{name}}" LOGIN;', 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";'], + default_ttl: 3600, + max_ttl: 0, + credential_type: 'password', + } + const draft = draftFromRole(dbRole, 'ro', data) + expect(draft.values.default_ttl).toBe('3600s') + expect(draft.values.max_ttl).toBe('') + expect(draft.extras).toEqual({ credential_type: 'password' }) + + draft.values.max_ttl = '24h' + expect(payloadFromDraft(dbRole, draft)).toEqual({ + db_name: 'pg', + creation_statements: data.creation_statements, + revocation_statements: [], + renew_statements: [], + rollback_statements: [], + default_ttl: '3600s', + max_ttl: '24h', + credential_type: 'password', + }) +}) + +test('statements split on blank lines, lists on commas or newlines', () => { + const d = emptyDraft(dbRole) + d.values.db_name = 'pg' + d.values.creation_statements = 'CREATE ROLE a,\n LOGIN;\n\nGRANT x;' + expect(payloadFromDraft(dbRole, d).creation_statements).toEqual(['CREATE ROLE a,\n LOGIN;', 'GRANT x;']) + + const a = emptyDraft(awsRole) + a.values.policy_arns = 'arn:1, arn:2\narn:3' + expect(payloadFromDraft(awsRole, a).policy_arns).toEqual(['arn:1', 'arn:2', 'arn:3']) +}) + +test('required fields are enforced', () => { + expect(() => payloadFromDraft(dbRole, emptyDraft(dbRole))).toThrow('Database config name is required.') + const d = emptyDraft(dbRole) + d.values.db_name = 'pg' + expect(() => payloadFromDraft(dbRole, d)).toThrow('Creation statements is required.') +}) + +test('select defaults to the first option and booleans are sent as booleans', () => { + const d = emptyDraft(sshRole) + expect(d.values.key_type).toBe('ca') + d.values.allow_user_certificates = true + const body = payloadFromDraft(sshRole, d) + expect(body).toMatchObject({ key_type: 'ca', allow_user_certificates: true, allow_host_certificates: false }) + expect(body).not.toHaveProperty('ttl') +}) + +test('generic roles are raw JSON and must be objects', () => { + const kind = engineFor('pki').roleKinds[0] + const d = emptyDraft(kind) + d.json = '{"allowed_domains":"example.com"}' + expect(payloadFromDraft(kind, d)).toEqual({ allowed_domains: 'example.com' }) + d.json = '{nope' + expect(() => payloadFromDraft(kind, d)).toThrow('not valid JSON') + d.json = '[]' + expect(() => payloadFromDraft(kind, d)).toThrow('must be a JSON object') +}) + +test('role API calls use the mount, kind path and an encoded name', async () => { + const c = new BaoClient('http://b', 't') + const req = vi.spyOn(c, 'request').mockResolvedValue({ data: { db_name: 'pg' } }) + vi.spyOn(c, 'list').mockResolvedValue(['b', 'a']) + + expect(await listRoles(c, 'database/', dbRole)).toEqual(['a', 'b']) + expect(c.list).toHaveBeenCalledWith('database/roles') + expect(await readRole(c, 'database/', dbRole, 'my role')).toEqual({ db_name: 'pg' }) + expect(req).toHaveBeenCalledWith('GET', 'database/roles/my%20role') + await writeRole(c, 'database/', dbRole, 'ro', { db_name: 'pg' }) + expect(req).toHaveBeenCalledWith('POST', 'database/roles/ro', { db_name: 'pg' }) + await deleteRole(c, 'database/', ENGINES.database.roleKinds[1], 'svc') + expect(req).toHaveBeenCalledWith('DELETE', 'database/static-roles/svc') +}) diff --git a/src/api/engines/roles.ts b/src/api/engines/roles.ts new file mode 100644 index 0000000..b145123 --- /dev/null +++ b/src/api/engines/roles.ts @@ -0,0 +1,105 @@ +import type { BaoClient } from '../bao' +import type { FieldDef, RoleKind } from './registry' + +const enc = encodeURIComponent + +export type RoleData = Record +export type DraftValue = string | boolean +export interface RoleDraft { + name: string + isNew: boolean + /** Values for the schema fields, keyed by field key. */ + values: Record + /** Raw JSON body, used when the role kind has no field schema. */ + json: string + /** Fields OpenBao returned that the schema does not know about; written back unchanged so edits don't drop them. */ + extras: RoleData +} + +export async function listRoles(c: BaoClient, mount: string, kind: RoleKind): Promise { + return (await c.list(`${mount}${kind.path}`)).sort((a, b) => a.localeCompare(b)) +} + +export async function readRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise { + const res = await c.request<{ data: RoleData }>('GET', `${mount}${kind.path}/${enc(name)}`) + return res.data +} + +export async function writeRole(c: BaoClient, mount: string, kind: RoleKind, name: string, body: RoleData): Promise { + await c.request('POST', `${mount}${kind.path}/${enc(name)}`, body) +} + +export async function deleteRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise { + await c.request('DELETE', `${mount}${kind.path}/${enc(name)}`) +} + +const listText = (v: unknown, sep: string) => (Array.isArray(v) ? v.join(sep) : typeof v === 'string' ? v : '') + +function fieldToDraft(f: FieldDef, v: unknown): DraftValue { + switch (f.type) { + case 'bool': + return v === true + case 'ttl': + // OpenBao reports durations as seconds; 0 means "unset / use default". + return typeof v === 'number' ? (v > 0 ? `${v}s` : '') : typeof v === 'string' ? v : '' + case 'list': + return listText(v, ', ') + case 'statements': + return listText(v, '\n\n') + default: + return typeof v === 'string' ? v : v == null ? '' : String(v) + } +} + +export function emptyDraft(kind: RoleKind): RoleDraft { + const values: Record = {} + for (const f of kind.fields) values[f.key] = f.type === 'bool' ? false : f.type === 'select' ? (f.options?.[0] ?? '') : '' + return { name: '', isNew: true, values, json: '{\n}', extras: {} } +} + +export function draftFromRole(kind: RoleKind, name: string, data: RoleData): RoleDraft { + const known = new Set(kind.fields.map((f) => f.key)) + const values: Record = {} + for (const f of kind.fields) values[f.key] = fieldToDraft(f, data[f.key]) + const extras = Object.fromEntries(Object.entries(data).filter(([k]) => !known.has(k))) + return { name, isNew: false, values, json: JSON.stringify(data, null, 2), extras } +} + +const splitList = (s: string) => + s + .split(/[,\n]/) + .map((x) => x.trim()) + .filter(Boolean) +const splitStatements = (s: string) => + s + .split(/\n\s*\n/) + .map((x) => x.trim()) + .filter(Boolean) + +/** Request body for a role write. Throws an Error with a user-facing message for invalid input. */ +export function payloadFromDraft(kind: RoleKind, draft: RoleDraft): RoleData { + if (kind.fields.length === 0) { + let parsed: unknown + try { + parsed = JSON.parse(draft.json) + } catch { + throw new Error('Role body is not valid JSON.') + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Role body must be a JSON object.') + return parsed as RoleData + } + const body: RoleData = { ...draft.extras } + for (const f of kind.fields) { + const v = draft.values[f.key] + if (f.type === 'bool') body[f.key] = v === true + else if (f.type === 'list') body[f.key] = splitList(String(v)) + else if (f.type === 'statements') body[f.key] = splitStatements(String(v)) + else if (String(v).trim() !== '') body[f.key] = String(v).trim() + else if (f.required) throw new Error(`${f.label} is required.`) + else delete body[f.key] + if ((f.type === 'list' || f.type === 'statements') && f.required && (body[f.key] as string[]).length === 0) { + throw new Error(`${f.label} is required.`) + } + } + return body +} diff --git a/src/features/secrets/EngineView.tsx b/src/features/secrets/EngineView.tsx index 18c3e55..710b90d 100644 --- a/src/features/secrets/EngineView.tsx +++ b/src/features/secrets/EngineView.tsx @@ -1,12 +1,17 @@ +import type { BaoClient } from '../../api/bao' import { engineFor } from '../../api/engines/registry' import type { Mount } from '../../api/secrets' +import { RolesPanel } from './RolesPanel' -/** Roles / Config / Leases for a dynamic secrets engine. Filled in by later phases. */ -export function EngineView({ mount }: { mount: Mount }) { +/** Roles (and, in later phases, Config / Leases) for a dynamic secrets engine. */ +export function EngineView({ client, mount }: { client: BaoClient; mount: Mount }) { const engine = engineFor(mount.type) return ( -

- {engine.label} engine at {mount.path}: role management is coming soon. -

+
+

+ {engine.label} · {mount.path} +

+ +
) } diff --git a/src/features/secrets/RoleEditor.tsx b/src/features/secrets/RoleEditor.tsx new file mode 100644 index 0000000..bfcc234 --- /dev/null +++ b/src/features/secrets/RoleEditor.tsx @@ -0,0 +1,121 @@ +import { useId, type FormEvent } from 'react' +import type { FieldDef, RoleKind } from '../../api/engines/registry' +import type { RoleDraft } from '../../api/engines/roles' + +function Field({ field, value, onChange }: { field: FieldDef; value: string | boolean; onChange: (v: string | boolean) => void }) { + const helpId = useId() + const help = field.help ? ( + + {field.help} + + ) : null + const describedBy = field.help ? helpId : undefined + + if (field.type === 'bool') { + return ( + + ) + } + if (field.type === 'select') { + return ( + + ) + } + if (field.type === 'textarea' || field.type === 'statements') { + return ( +