diff --git a/src/api/engines/config.test.ts b/src/api/engines/config.test.ts new file mode 100644 index 0000000..72e6e54 --- /dev/null +++ b/src/api/engines/config.test.ts @@ -0,0 +1,83 @@ +import { expect, test, vi } from 'vitest' +import { BaoClient, BaoError } from '../bao' +import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from './config' +import { generateCreds } from './creds' +import { revokeLease } from './leases' +import { ENGINES } from './registry' +import { draftFromRole, emptyDraft, payloadFromDraft } from './roles' + +const conn = ENGINES.database.configs[0] +const aws = ENGINES.aws.configs[0] +const awsCreds = ENGINES.aws.roleKinds[0].creds[0] + +test('named configs are addressed by name and flatten connection_details', async () => { + const c = new BaoClient('http://b', 't') + const req = vi.spyOn(c, 'request').mockResolvedValue({ + data: { plugin_name: 'postgresql-database-plugin', allowed_roles: ['ro'], connection_details: { connection_url: 'postgresql://x', username: 'bao' } }, + }) + vi.spyOn(c, 'list').mockResolvedValue(['b', 'a']) + + expect(await listConfigs(c, 'database/', conn)).toEqual(['a', 'b']) + expect(await readConfig(c, 'database/', conn, 'my pg')).toMatchObject({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao' }) + expect(req).toHaveBeenCalledWith('GET', 'database/config/my%20pg') + await writeConfig(c, 'database/', conn, { a: 1 }, 'pg') + expect(req).toHaveBeenCalledWith('POST', 'database/config/pg', { a: 1 }) + await deleteConfig(c, 'database/', conn, 'pg') + expect(req).toHaveBeenCalledWith('DELETE', 'database/config/pg') + await runAction(c, 'database/', conn.actions![0], 'pg') + expect(req).toHaveBeenCalledWith('POST', 'database/rotate-root/pg', {}) +}) + +test('single configs use the bare path and read as null when unconfigured', async () => { + const c = new BaoClient('http://b', 't') + const req = vi.spyOn(c, 'request').mockRejectedValue(new BaoError('not-found', 'nope', 404)) + expect(await readConfig(c, 'aws/', aws)).toBeNull() + expect(req).toHaveBeenCalledWith('GET', 'aws/config/root') + req.mockRejectedValue(new BaoError('forbidden', 'denied', 403)) + await expect(readConfig(c, 'aws/', aws)).rejects.toThrow('denied') +}) + +test('an engine that errors instead of 404ing reads as unconfigured only for its own message', async () => { + const c = new BaoClient('http://b', 't') + const ca = ENGINES.ssh.configs[0] + const req = vi.spyOn(c, 'request').mockRejectedValue(new BaoError('server', 'No default issuer currently configured', 400)) + expect(await readConfig(c, 'ssh/', ca)).toBeNull() + req.mockRejectedValue(new BaoError('server', 'something else', 500)) + await expect(readConfig(c, 'ssh/', ca)).rejects.toThrow('something else') + req.mockRejectedValue(new BaoError('server', 'No default issuer currently configured', 400)) + await expect(readConfig(c, 'aws/', aws)).rejects.toThrow('No default issuer') +}) + +test('secret fields are never prefilled and are omitted when left blank', () => { + const draft = draftFromRole(conn, 'pg', { plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao', password: 'leaked' }) + expect(draft.values.password).toBe('') + expect(payloadFromDraft(conn, draft)).not.toHaveProperty('password') + draft.values.password = 's3cret' + expect(payloadFromDraft(conn, draft)).toMatchObject({ password: 's3cret' }) + expect(emptyDraft(conn).values.password).toBe('') +}) + +test('credential requests: POST sends inputs, result is normalised', async () => { + const c = new BaoClient('http://b', 't') + const req = vi.spyOn(c, 'request').mockResolvedValue({ + lease_id: 'aws/creds/ci/abc', + lease_duration: 3600, + renewable: true, + data: { access_key: 'AK', secret_key: 'SK' }, + warnings: null, + }) + const creds = await generateCreds(c, 'aws/', awsCreds, 'ci', { ttl: '1h' }) + expect(req).toHaveBeenCalledWith('POST', 'aws/creds/ci', { ttl: '1h' }) + expect(creds).toEqual({ leaseId: 'aws/creds/ci/abc', leaseDuration: 3600, renewable: true, data: { access_key: 'AK', secret_key: 'SK' }, warnings: [] }) + + const dbCreds = ENGINES.database.roleKinds[0].creds[0] + await generateCreds(c, 'database/', dbCreds, 'ro', { ignored: true }) + expect(req).toHaveBeenLastCalledWith('GET', 'database/creds/ro', undefined) +}) + +test('revoking a lease', async () => { + const c = new BaoClient('http://b', 't') + const req = vi.spyOn(c, 'request').mockResolvedValue(undefined) + await revokeLease(c, 'database/creds/ro/xyz') + expect(req).toHaveBeenCalledWith('PUT', 'sys/leases/revoke', { lease_id: 'database/creds/ro/xyz' }) +}) diff --git a/src/api/engines/config.ts b/src/api/engines/config.ts new file mode 100644 index 0000000..b52c930 --- /dev/null +++ b/src/api/engines/config.ts @@ -0,0 +1,42 @@ +import { BaoError, type BaoClient } from '../bao' +import type { ActionDef, ConfigKind } from './registry' +import type { RoleData } from './roles' + +const enc = encodeURIComponent +const where = (mount: string, kind: ConfigKind, name?: string) => + kind.named ? `${mount}${kind.path}/${enc(name ?? '')}` : `${mount}${kind.path}` + +/** Names of the configs of a named kind (database connections). */ +export async function listConfigs(c: BaoClient, mount: string, kind: ConfigKind): Promise { + return (await c.list(`${mount}${kind.path}`)).sort((a, b) => a.localeCompare(b)) +} + +/** + * Reads a config, flattening `kind.nested` into the top level. Returns null when nothing is configured yet. + * OpenBao never returns write-only values such as passwords, so none can appear here. + */ +export async function readConfig(c: BaoClient, mount: string, kind: ConfigKind, name?: string): Promise { + try { + const res = await c.request<{ data: RoleData } | undefined>('GET', where(mount, kind, name)) + const data = res?.data + if (!data) return null + const nested = kind.nested ? data[kind.nested] : undefined + return nested && typeof nested === 'object' ? { ...data, ...(nested as RoleData) } : data + } catch (e) { + if (e instanceof BaoError && e.kind === 'not-found') return null + if (e instanceof BaoError && kind.unsetMessage && e.message.toLowerCase().includes(kind.unsetMessage)) return null + throw e + } +} + +export async function writeConfig(c: BaoClient, mount: string, kind: ConfigKind, body: RoleData, name?: string): Promise { + await c.request('POST', where(mount, kind, name), body) +} + +export async function deleteConfig(c: BaoClient, mount: string, kind: ConfigKind, name?: string): Promise { + await c.request('DELETE', where(mount, kind, name)) +} + +export async function runAction(c: BaoClient, mount: string, action: ActionDef, name?: string): Promise { + await c.request('POST', `${mount}${action.path.replace('{name}', enc(name ?? ''))}`, action.body ?? {}) +} diff --git a/src/api/engines/creds.ts b/src/api/engines/creds.ts new file mode 100644 index 0000000..d393358 --- /dev/null +++ b/src/api/engines/creds.ts @@ -0,0 +1,34 @@ +import type { BaoClient } from '../bao' +import type { CredKind } from './registry' +import type { RoleData } from './roles' + +/** Credentials as issued. These are secrets: show them once and never put them in a query cache. */ +export interface Credentials { + /** Empty for credentials without a lease (database static roles). */ + leaseId: string + /** Seconds; 0 when the credentials have no expiry. */ + leaseDuration: number + renewable: boolean + data: Record + warnings: string[] +} + +interface CredResponse { + lease_id?: string + lease_duration?: number + renewable?: boolean + data?: Record + warnings?: string[] | null +} + +export async function generateCreds(c: BaoClient, mount: string, kind: CredKind, role: string, body: RoleData): Promise { + const path = `${mount}${kind.path(role)}` + const res = await c.request(kind.method, path, kind.method === 'POST' ? body : undefined) + return { + leaseId: res.lease_id ?? '', + leaseDuration: res.lease_duration ?? 0, + renewable: res.renewable ?? false, + data: res.data ?? {}, + warnings: res.warnings ?? [], + } +} diff --git a/src/api/engines/leases.ts b/src/api/engines/leases.ts new file mode 100644 index 0000000..cf62272 --- /dev/null +++ b/src/api/engines/leases.ts @@ -0,0 +1,6 @@ +import type { BaoClient } from '../bao' + +/** Revokes one lease, which also deletes the credentials it issued (database user, AWS key, ...). */ +export async function revokeLease(c: BaoClient, leaseId: string): Promise { + await c.request('PUT', 'sys/leases/revoke', { lease_id: leaseId }) +} diff --git a/src/api/engines/registry.ts b/src/api/engines/registry.ts index 2eee0ce..e4e1f13 100644 --- a/src/api/engines/registry.ts +++ b/src/api/engines/registry.ts @@ -14,6 +14,8 @@ export type FieldType = | 'statements' | 'bool' | 'select' + /** Write-only value (password, private key). Never prefilled; left blank it is omitted so the stored value is kept. */ + | 'secret' export interface FieldDef { key: string @@ -22,6 +24,47 @@ export interface FieldDef { required?: boolean options?: string[] help?: string + /** Render as a textarea (secret fields such as PEM keys). */ + multiline?: boolean +} + +/** How to ask OpenBao for credentials (or a signed certificate) for a role. */ +export interface CredKind { + id: string + label: string + /** Path relative to the mount for a given role name. */ + path: (role: string) => string + method: 'GET' | 'POST' + /** Request parameters; only sent for POST. */ + inputs: FieldDef[] +} + +/** A one-off call on a config, e.g. rotating the root credentials. */ +export interface ActionDef { + id: string + label: string + /** Path relative to the mount; "{name}" is replaced with the config name for named configs. */ + path: string + body?: Record + confirm: { title: string; message: string; confirmLabel: string } +} + +/** Engine configuration: a named list (database connections) or a single endpoint (aws root, ssh CA). */ +export interface ConfigKind { + id: string + label: string + /** Path relative to the mount; for named configs the name is appended. */ + path: string + named: boolean + fields: FieldDef[] + /** Reads put these under a nested key (database: connection_details); merged into the form values. */ + nested?: string + /** Read-only values to display after loading, e.g. the SSH CA public key. */ + shown?: { key: string; label: string }[] + actions?: ActionDef[] + deletable?: boolean + /** Part of the error OpenBao returns when nothing is configured yet, for engines that don't answer 404. */ + unsetMessage?: string } /** One family of roles under a mount, e.g. database "roles" and "static-roles". */ @@ -32,6 +75,8 @@ export interface RoleKind { path: string /** Empty means the role is edited as raw JSON (generic engines). */ fields: FieldDef[] + /** Ways to get credentials for a role of this kind. */ + creds: CredKind[] } /** Describes a dynamic secrets engine the UI can manage. Grows in later phases (creds, config). */ @@ -40,6 +85,7 @@ export interface EngineDef { type: string label: string roleKinds: RoleKind[] + configs: ConfigKind[] } const DATABASE_ROLE: RoleKind = { @@ -61,6 +107,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: [] }], } const DATABASE_STATIC_ROLE: RoleKind = { @@ -73,6 +120,9 @@ const DATABASE_STATIC_ROLE: RoleKind = { { key: 'rotation_statements', label: 'Rotation statements', type: 'statements' }, { 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: [] }, + ], } const AWS_ROLE: RoleKind = { @@ -96,6 +146,18 @@ const AWS_ROLE: RoleKind = { { key: 'permissions_boundary_arn', label: 'Permissions boundary ARN', type: 'text' }, { key: 'user_path', label: 'IAM user path', type: 'text' }, ], + creds: [ + { + id: 'creds', + label: 'Generate credentials', + path: (r) => `creds/${encodeURIComponent(r)}`, + method: 'POST', + 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.' }, + ], + }, + ], } const SSH_ROLE: RoleKind = { @@ -113,12 +175,147 @@ const SSH_ROLE: RoleKind = { { key: 'allow_host_certificates', label: 'Allow host certificates', type: 'bool' }, { key: 'allowed_extensions', label: 'Allowed extensions', type: 'text' }, ], + creds: [ + { + id: 'sign', + label: 'Sign a public key (CA)', + path: (r) => `sign/${encodeURIComponent(r)}`, + method: 'POST', + inputs: [ + { key: 'public_key', label: 'Public key', type: 'textarea', required: true }, + { key: 'valid_principals', label: 'Valid principals', type: 'text', help: 'Comma separated.' }, + { key: 'ttl', label: 'TTL', type: 'ttl' }, + { key: 'cert_type', label: 'Certificate type', type: 'select', options: ['user', 'host'] }, + ], + }, + { + id: 'otp', + label: 'Generate an OTP', + path: (r) => `creds/${encodeURIComponent(r)}`, + method: 'POST', + inputs: [ + { key: 'ip', label: 'Target IP', type: 'text', required: true }, + { key: 'username', label: 'Username', type: 'text' }, + ], + }, + ], +} + +const DATABASE_CONNECTION: ConfigKind = { + id: 'connections', + label: 'Connections', + path: 'config', + named: true, + nested: 'connection_details', + deletable: true, + fields: [ + { + key: 'plugin_name', + label: 'Plugin', + type: 'select', + required: true, + options: ['postgresql-database-plugin', 'mysql-database-plugin', 'mongodb-database-plugin', 'mssql-database-plugin'], + }, + { + key: 'connection_url', + label: 'Connection URL', + type: 'text', + required: true, + help: 'e.g. postgresql://{{username}}:{{password}}@db:5432/app', + }, + { key: 'allowed_roles', label: 'Allowed roles', type: 'list', help: 'Role names, or * for any.' }, + { key: 'username', label: 'Admin username', type: 'text' }, + { key: 'password', label: 'Admin password', type: 'secret' }, + { key: 'verify_connection', label: 'Verify the connection when saving', type: 'bool' }, + ], + actions: [ + { + id: 'rotate-root', + label: 'Rotate root credentials', + path: 'rotate-root/{name}', + confirm: { + title: 'Rotate the root credentials?', + message: 'OpenBao will change the admin password, and only OpenBao will know the new one.', + confirmLabel: 'Rotate', + }, + }, + { + id: 'reset', + label: 'Reset connection', + path: 'reset/{name}', + confirm: { title: 'Reset the connection?', message: 'The plugin connection is closed and reopened.', confirmLabel: 'Reset' }, + }, + ], +} + +const AWS_ROOT: ConfigKind = { + id: 'root', + label: 'Root credentials', + path: 'config/root', + named: false, + fields: [ + { key: 'access_key', label: 'Access key', type: 'text' }, + { key: 'secret_key', label: 'Secret key', type: 'secret' }, + { key: 'region', label: 'Region', type: 'text' }, + { key: 'iam_endpoint', label: 'IAM endpoint', type: 'text' }, + { key: 'sts_endpoint', label: 'STS endpoint', type: 'text' }, + ], + actions: [ + { + id: 'rotate-root', + label: 'Rotate root credentials', + path: 'config/rotate-root', + confirm: { + title: 'Rotate the root access key?', + message: 'OpenBao will create a new access key and delete the old one.', + confirmLabel: 'Rotate', + }, + }, + ], +} + +const AWS_LEASE: ConfigKind = { + id: 'lease', + label: 'Lease', + path: 'config/lease', + named: false, + fields: [ + { key: 'lease', label: 'Default lease', type: 'ttl' }, + { key: 'lease_max', label: 'Max lease', type: 'ttl' }, + ], +} + +const SSH_CA: ConfigKind = { + id: 'ca', + label: 'Signing CA', + path: 'config/ca', + named: false, + deletable: true, + unsetMessage: 'no default issuer', + fields: [ + { key: 'public_key', label: 'Public key', type: 'textarea', help: 'Import a key pair, or generate one below.' }, + { key: 'private_key', label: 'Private key', type: 'secret', multiline: true }, + ], + shown: [{ key: 'public_key', label: 'Current CA public key' }], + actions: [ + { + id: 'generate', + label: 'Generate signing key', + path: 'config/ca', + body: { generate_signing_key: true }, + confirm: { + title: 'Generate a new signing key?', + message: 'This replaces any existing CA, so certificates signed by the old key stop being trusted.', + confirmLabel: 'Generate', + }, + }, + ], } export const ENGINES: Record = { - 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] }, + database: { type: 'database', label: 'Database', roleKinds: [DATABASE_ROLE, DATABASE_STATIC_ROLE], configs: [DATABASE_CONNECTION] }, + aws: { type: 'aws', label: 'AWS', roleKinds: [AWS_ROLE], configs: [AWS_ROOT, AWS_LEASE] }, + ssh: { type: 'ssh', label: 'SSH', roleKinds: [SSH_ROLE], configs: [SSH_CA] }, } /** Engine types that are managed as plain secret stores or by the system, not as dynamic engines. */ @@ -126,7 +323,14 @@ 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, roleKinds: [{ id: 'roles', label: 'Roles', path: 'roles', fields: [] }] } + return ( + ENGINES[type] ?? { + type, + label: type, + roleKinds: [{ id: 'roles', label: 'Roles', path: 'roles', fields: [], creds: [] }], + configs: [], + } + ) } export type MountKind = 'kv' | 'dynamic' diff --git a/src/api/engines/roles.integration.test.ts b/src/api/engines/roles.integration.test.ts index 7c78adb..bc528a3 100644 --- a/src/api/engines/roles.integration.test.ts +++ b/src/api/engines/roles.integration.test.ts @@ -1,5 +1,8 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest' import { BaoClient } from '../bao' +import { readConfig, runAction, writeConfig, deleteConfig } from './config' +import { generateCreds } from './creds' +import { revokeLease } from './leases' import { listMounts } from '../secrets' import { ENGINES } from './registry' import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles' @@ -8,13 +11,23 @@ const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', pr const sfx = Math.random().toString(36).slice(2, 8) const mount = `it-ssh-${sfx}/` const kind = ENGINES.ssh.roleKinds[0] +const awsMount = `it-aws-${sfx}/` +// Not every OpenBao build bundles the AWS engine (some ship it as an external plugin). +let awsAvailable = false +// A throwaway public key made only for this test; there is no matching private key anywhere. +const PUBLIC_KEY = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDI/MhHH9Rd3dBZwAa4gQOkxfuw0ogMWlO2G4rlINbfv it' beforeAll(async () => { await client.request('POST', `sys/mounts/${mount.slice(0, -1)}`, { type: 'ssh' }) + awsAvailable = await client + .request('POST', `sys/mounts/${awsMount.slice(0, -1)}`, { type: 'aws' }) + .then(() => true) + .catch(() => false) }) afterAll(async () => { await client.request('DELETE', `sys/mounts/${mount.slice(0, -1)}`).catch(() => {}) + await client.request('DELETE', `sys/mounts/${awsMount.slice(0, -1)}`).catch(() => {}) }) describe('dynamic engine roles (ssh)', () => { @@ -47,3 +60,49 @@ describe('dynamic engine roles (ssh)', () => { expect(await listRoles(client, mount, kind)).toEqual([]) }) }) + +describe('dynamic engine config and credentials', () => { + const ca = ENGINES.ssh.configs[0] + + test('an unconfigured CA reads as null, then generate, sign and delete', async () => { + expect(await readConfig(client, mount, ca)).toBeNull() + + await runAction(client, mount, ca.actions![0]) + const cfg = await readConfig(client, mount, ca) + expect(cfg?.public_key).toMatch(/^ssh-rsa /) + + const role = emptyDraft(kind) + role.values.allow_user_certificates = true + role.values.allowed_users = '*' + role.values.default_user = 'alice' + role.values.ttl = '10m' + await writeRole(client, mount, kind, 'signer', payloadFromDraft(kind, role)) + + const sign = kind.creds[0] + const out = await generateCreds(client, mount, sign, 'signer', { public_key: PUBLIC_KEY }) + expect(String(out.data.signed_key)).toMatch(/^ssh-ed25519-cert-v01@openssh.com /) + + await deleteConfig(client, mount, ca) + expect(await readConfig(client, mount, ca)).toBeNull() + }) + + test('OTP credentials come with a lease that can be revoked', async () => { + const role = emptyDraft(kind) + role.values.key_type = 'otp' + role.values.default_user = 'alice' + role.values.cidr_list = '10.0.0.0/8' + await writeRole(client, mount, kind, 'otp', payloadFromDraft(kind, role)) + + const out = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.3' }) + expect(out.leaseId).toContain('/creds/otp/') + expect(out.data.key).toBeTruthy() + await revokeLease(client, out.leaseId) + }) + + test('single-endpoint config round-trips (aws lease)', async (ctx) => { + if (!awsAvailable) ctx.skip() + const lease = ENGINES.aws.configs[1] + await writeConfig(client, awsMount, lease, { lease: '30m', lease_max: '2h' }) + expect(await readConfig(client, awsMount, lease)).toMatchObject({ lease: '30m0s', lease_max: '2h0m0s' }) + }) +}) diff --git a/src/api/engines/roles.ts b/src/api/engines/roles.ts index b145123..01b86c5 100644 --- a/src/api/engines/roles.ts +++ b/src/api/engines/roles.ts @@ -1,6 +1,11 @@ import type { BaoClient } from '../bao' import type { FieldDef, RoleKind } from './registry' +/** Anything with a field schema: a role kind, a config kind, or a credential request. */ +export interface Schema { + fields: FieldDef[] +} + const enc = encodeURIComponent export type RoleData = Record @@ -42,6 +47,8 @@ function fieldToDraft(f: FieldDef, v: unknown): DraftValue { 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 'secret': + return '' case 'list': return listText(v, ', ') case 'statements': @@ -51,13 +58,13 @@ function fieldToDraft(f: FieldDef, v: unknown): DraftValue { } } -export function emptyDraft(kind: RoleKind): RoleDraft { +export function emptyDraft(kind: Schema): 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 { +export function draftFromRole(kind: Schema, 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]) @@ -77,7 +84,7 @@ const splitStatements = (s: string) => .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 { +export function payloadFromDraft(kind: Schema, draft: RoleDraft): RoleData { if (kind.fields.length === 0) { let parsed: unknown try { diff --git a/src/features/secrets/ConfigPanel.test.tsx b/src/features/secrets/ConfigPanel.test.tsx new file mode 100644 index 0000000..a98086a --- /dev/null +++ b/src/features/secrets/ConfigPanel.test.tsx @@ -0,0 +1,97 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { BaoClient } from '../../api/bao' +import * as config from '../../api/engines/config' +import { ENGINES } from '../../api/engines/registry' +import { ConfigPanel } from './ConfigPanel' + +vi.mock('../../api/engines/config') + +const client = new BaoClient('http://b', 't') +const conn = ENGINES.database.configs[0] + +function renderPanel(type: keyof typeof ENGINES) { + render( + + + , + ) + return userEvent.setup() +} + +beforeEach(() => { + vi.mocked(config.listConfigs).mockResolvedValue(['pg']) +}) +afterEach(() => vi.resetAllMocks()) + +test('creates a database connection, sending the password only when typed', async () => { + vi.mocked(config.writeConfig).mockResolvedValue() + const user = renderPanel('database') + await user.click(await screen.findByRole('button', { name: 'New connection' })) + await user.type(screen.getByLabelText('Connection name'), 'main') + await user.type(screen.getByLabelText(/^Connection URL/), 'postgresql://u:p@db/app') + await user.type(screen.getByLabelText('Admin password'), 's3cret') + await user.click(screen.getByRole('button', { name: 'Save' })) + expect(config.writeConfig).toHaveBeenCalledWith( + client, + 'database/', + conn, + expect.objectContaining({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://u:p@db/app', password: 's3cret' }), + 'main', + ) +}) + +test('editing keeps the stored password: blank is omitted and nothing is prefilled', async () => { + vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao', allowed_roles: ['ro'] }) + vi.mocked(config.writeConfig).mockResolvedValue() + const user = renderPanel('database') + await user.click(await screen.findByRole('button', { name: 'Edit pg' })) + expect(await screen.findByLabelText('Admin password')).toHaveValue('') + expect(screen.getByLabelText('Connection name')).toBeDisabled() + await user.click(screen.getByRole('button', { name: 'Save' })) + const body = vi.mocked(config.writeConfig).mock.calls[0][3] + expect(body).toMatchObject({ connection_url: 'postgresql://x', allowed_roles: ['ro'], username: 'bao' }) + expect(body).not.toHaveProperty('password') +}) + +test('rotating root credentials asks first', async () => { + vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x' }) + vi.mocked(config.runAction).mockResolvedValue() + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false) + const user = renderPanel('database') + await user.click(await screen.findByRole('button', { name: 'Edit pg' })) + await user.click(await screen.findByRole('button', { name: 'Rotate root credentials' })) + expect(config.runAction).not.toHaveBeenCalled() + + confirm.mockReturnValue(true) + await user.click(screen.getByRole('button', { name: 'Rotate root credentials' })) + expect(config.runAction).toHaveBeenCalledWith(client, 'database/', conn.actions![0], 'pg') +}) + +test('aws shows root and lease configs, loaded from their own endpoints', async () => { + vi.mocked(config.readConfig).mockImplementation(async (_c, _m, kind) => + kind.id === 'root' ? { access_key: 'AKIA1', region: 'eu-west-1' } : null, + ) + renderPanel('aws') + expect(await screen.findByDisplayValue('AKIA1')).toBeInTheDocument() + expect(screen.getByLabelText('Secret key')).toHaveValue('') + expect(screen.getByLabelText('Default lease')).toBeInTheDocument() +}) + +test('ssh CA: shows the public key and generating asks first', async () => { + vi.mocked(config.readConfig).mockResolvedValue({ public_key: 'ssh-rsa AAAAca' }) + vi.mocked(config.runAction).mockResolvedValue() + vi.spyOn(window, 'confirm').mockReturnValue(true) + const user = renderPanel('ssh') + expect(await screen.findByLabelText('Current CA public key')).toHaveValue('ssh-rsa AAAAca') + await user.click(screen.getByRole('button', { name: 'Generate signing key' })) + expect(config.runAction).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.configs[0].actions![0], undefined) +}) + +test('shows the load error', async () => { + vi.mocked(config.listConfigs).mockRejectedValue(new Error('permission denied')) + renderPanel('database') + expect(await screen.findByRole('alert')).toHaveTextContent('permission denied') +}) diff --git a/src/features/secrets/ConfigPanel.tsx b/src/features/secrets/ConfigPanel.tsx new file mode 100644 index 0000000..ddb44e9 --- /dev/null +++ b/src/features/secrets/ConfigPanel.tsx @@ -0,0 +1,189 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useState } from 'react' +import type { BaoClient } from '../../api/bao' +import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from '../../api/engines/config' +import type { ConfigKind, EngineDef } from '../../api/engines/registry' +import { draftFromRole, emptyDraft, payloadFromDraft, type RoleData, type RoleDraft } from '../../api/engines/roles' +import { ListState } from '../shared/ListState' +import { useConfirm } from '../shared/useConfirm' +import { RoleEditor } from './RoleEditor' + +function ConfigEditor({ client, mount, kind, name, initial, onDone }: { + client: BaoClient + mount: string + kind: ConfigKind + /** Config name for named kinds; undefined for single-endpoint configs. */ + name?: string + /** Existing values (null when nothing is configured yet). */ + initial: RoleData | null + onDone: () => void +}) { + const qc = useQueryClient() + const confirm = useConfirm() + const [draft, setDraft] = useState(() => + initial ? draftFromRole(kind, name ?? '', initial) : { ...emptyDraft(kind), name: name ?? '' }, + ) + const [formError, setFormError] = useState(null) + const done = () => qc.invalidateQueries({ queryKey: ['engine-config', mount, kind.id] }) + + const save = useMutation({ + mutationFn: (d: RoleDraft) => writeConfig(client, mount, kind, payloadFromDraft(kind, d), kind.named ? d.name.trim() : undefined), + onSuccess: async () => { + await done() + onDone() + }, + }) + const act = useMutation({ + mutationFn: (id: string) => runAction(client, mount, kind.actions!.find((a) => a.id === id)!, name), + onSuccess: done, + }) + const remove = useMutation({ + mutationFn: () => deleteConfig(client, mount, kind, name), + onSuccess: async () => { + await done() + onDone() + }, + }) + + const shown = kind.shown?.filter((s) => typeof initial?.[s.key] === 'string' && initial[s.key] !== '') + return ( +
+ {shown?.map((s) => ( +