Secrets: engine config editors and one-time credential generation

Adds Config tab (database connections with rotate/reset, aws root and
lease, ssh CA with generate/import) and a Generate action on roles
(database/static creds, aws creds, ssh sign and OTP). Secret inputs are
write-only: never prefilled and omitted when blank so the stored value
is kept. Issued credentials live only in a gcTime-0 mutation and are
shown once, with revoke-now for leased credentials.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-11-09 13:30:08 +00:00
1 parent 4fa7ff1497
commit 48746e2150
15 files changed
+1089 -18

No files matched your search

+83
View File
@@ -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' })
})
+42
View File
@@ -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<string[]> {
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<RoleData | null> {
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<void> {
await c.request('POST', where(mount, kind, name), body)
}
export async function deleteConfig(c: BaoClient, mount: string, kind: ConfigKind, name?: string): Promise<void> {
await c.request('DELETE', where(mount, kind, name))
}
export async function runAction(c: BaoClient, mount: string, action: ActionDef, name?: string): Promise<void> {
await c.request('POST', `${mount}${action.path.replace('{name}', enc(name ?? ''))}`, action.body ?? {})
}
+34
View File
@@ -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<string, unknown>
warnings: string[]
}
interface CredResponse {
lease_id?: string
lease_duration?: number
renewable?: boolean
data?: Record<string, unknown>
warnings?: string[] | null
}
export async function generateCreds(c: BaoClient, mount: string, kind: CredKind, role: string, body: RoleData): Promise<Credentials> {
const path = `${mount}${kind.path(role)}`
const res = await c.request<CredResponse>(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 ?? [],
}
}
+6
View File
@@ -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<void> {
await c.request('PUT', 'sys/leases/revoke', { lease_id: leaseId })
}
+208 -4
View File
@@ -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<string, unknown>
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<string, EngineDef> = {
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'
+59
View File
@@ -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' })
})
})
+10 -3
View File
@@ -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<string, unknown>
@@ -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<string, DraftValue> = {}
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<string, DraftValue> = {}
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 {