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:
1 parent
4fa7ff1497
commit
48746e2150
15 files changed
+1089
-18
No files matched your search
@@ -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' })
|
||||
})
|
||||
@@ -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 ?? {})
|
||||
}
|
||||
@@ -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 ?? [],
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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'
|
||||
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<ConfigPanel client={client} mount={`${type}/`} engine={ENGINES[type]} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
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')
|
||||
})
|
||||
@@ -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<RoleDraft>(() =>
|
||||
initial ? draftFromRole(kind, name ?? '', initial) : { ...emptyDraft(kind), name: name ?? '' },
|
||||
)
|
||||
const [formError, setFormError] = useState<string | null>(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 (
|
||||
<div>
|
||||
{shown?.map((s) => (
|
||||
<label key={s.key}>
|
||||
{s.label}
|
||||
<textarea readOnly rows={3} value={String(initial?.[s.key])} />
|
||||
</label>
|
||||
))}
|
||||
<RoleEditor
|
||||
kind={kind}
|
||||
noun={kind.named ? 'connection' : kind.label.toLowerCase()}
|
||||
showName={kind.named}
|
||||
draft={draft}
|
||||
pending={save.isPending}
|
||||
error={formError ?? save.error?.message ?? null}
|
||||
onChange={setDraft}
|
||||
onSubmit={() => {
|
||||
setFormError(null)
|
||||
try {
|
||||
payloadFromDraft(kind, draft)
|
||||
} catch (e) {
|
||||
setFormError((e as Error).message)
|
||||
return
|
||||
}
|
||||
save.mutate(draft)
|
||||
}}
|
||||
onCancel={onDone}
|
||||
/>
|
||||
{(initial !== null || !kind.named) &&
|
||||
kind.actions?.map((a) => (
|
||||
<button
|
||||
key={a.id}
|
||||
type="button"
|
||||
disabled={act.isPending}
|
||||
onClick={async () => {
|
||||
if (await confirm(a.confirm)) act.mutate(a.id)
|
||||
}}
|
||||
>
|
||||
{a.label}
|
||||
</button>
|
||||
))}
|
||||
{kind.deletable && initial !== null && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: `Delete ${kind.named ? `“${name}”` : kind.label.toLowerCase()}?`, message: 'This cannot be undone.', confirmLabel: 'Delete' }))
|
||||
remove.mutate()
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
{act.isSuccess && <p role="status">Done.</p>}
|
||||
{act.error && <p role="alert">{act.error.message}</p>}
|
||||
{remove.error && <p role="alert">{remove.error.message}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SingleConfig({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
|
||||
const q = useQuery({ queryKey: ['engine-config', mount, kind.id, ''], queryFn: () => readConfig(client, mount, kind) })
|
||||
if (q.isPending) return <p role="status">Loading…</p>
|
||||
if (q.error) return <p role="alert">{q.error.message}</p>
|
||||
// `key` remounts the form with fresh values after a save or action reloads the config.
|
||||
return (
|
||||
<ConfigEditor
|
||||
key={JSON.stringify(q.data)}
|
||||
client={client}
|
||||
mount={mount}
|
||||
kind={kind}
|
||||
initial={q.data}
|
||||
onDone={() => void q.refetch()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function NamedConfigs({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
|
||||
const [editing, setEditing] = useState<{ name?: string; initial: RoleData | null } | null>(null)
|
||||
const names = useQuery({ queryKey: ['engine-config', mount, kind.id], queryFn: () => listConfigs(client, mount, kind) })
|
||||
const open = useMutation({
|
||||
mutationFn: (name: string) => readConfig(client, mount, kind, name),
|
||||
onSuccess: (initial, name) => setEditing({ name, initial }),
|
||||
})
|
||||
return (
|
||||
<div>
|
||||
<ListState query={names} empty={`No ${kind.label.toLowerCase()} yet.`} />
|
||||
{!!names.data?.length && (
|
||||
<table aria-label={kind.label}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{names.data.map((n) => (
|
||||
<tr key={n}>
|
||||
<td>{n}</td>
|
||||
<td>
|
||||
<button type="button" aria-label={`Edit ${n}`} onClick={() => open.mutate(n)}>
|
||||
Edit
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{open.error && <p role="alert">{open.error.message}</p>}
|
||||
{!editing && (
|
||||
<button type="button" onClick={() => setEditing({ initial: null })}>
|
||||
New connection
|
||||
</button>
|
||||
)}
|
||||
{editing && (
|
||||
<ConfigEditor
|
||||
key={editing.name ?? 'new'}
|
||||
client={client}
|
||||
mount={mount}
|
||||
kind={kind}
|
||||
name={editing.name}
|
||||
initial={editing.initial}
|
||||
onDone={() => setEditing(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ConfigPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
|
||||
return (
|
||||
<section aria-label="Config">
|
||||
{engine.configs.map((kind) => (
|
||||
<div key={kind.id}>
|
||||
<h3>{kind.label}</h3>
|
||||
{kind.named ? <NamedConfigs client={client} mount={mount} kind={kind} /> : <SingleConfig client={client} mount={mount} kind={kind} />}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,36 @@
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { engineFor } from '../../api/engines/registry'
|
||||
import type { Mount } from '../../api/secrets'
|
||||
import { ConfigPanel } from './ConfigPanel'
|
||||
import { RolesPanel } from './RolesPanel'
|
||||
|
||||
/** Roles (and, in later phases, Config / Leases) for a dynamic secrets engine. */
|
||||
type Tab = 'roles' | 'config'
|
||||
|
||||
/** Roles and Config (and, in a later phase, Leases) for a dynamic secrets engine. */
|
||||
export function EngineView({ client, mount }: { client: BaoClient; mount: Mount }) {
|
||||
const engine = engineFor(mount.type)
|
||||
const [tab, setTab] = useState<Tab>('roles')
|
||||
const tabs: { id: Tab; label: string }[] = [{ id: 'roles', label: 'Roles' }]
|
||||
if (engine.configs.length > 0) tabs.push({ id: 'config', label: 'Config' })
|
||||
const current = tabs.some((t) => t.id === tab) ? tab : 'roles'
|
||||
|
||||
return (
|
||||
<div className="engine-view">
|
||||
<h2>
|
||||
{engine.label} · {mount.path}
|
||||
</h2>
|
||||
<RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />
|
||||
{tabs.length > 1 && (
|
||||
<div role="tablist" aria-label="Engine" className="tabs">
|
||||
{tabs.map((t) => (
|
||||
<button key={t.id} type="button" role="tab" aria-selected={t.id === current} onClick={() => setTab(t.id)}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{current === 'roles' && <RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
{current === 'config' && <ConfigPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, expect, test, vi } from 'vitest'
|
||||
import { BaoClient } from '../../api/bao'
|
||||
import * as creds from '../../api/engines/creds'
|
||||
import * as leases from '../../api/engines/leases'
|
||||
import { ENGINES } from '../../api/engines/registry'
|
||||
import { GenerateCreds } from './GenerateCreds'
|
||||
|
||||
vi.mock('../../api/engines/creds')
|
||||
vi.mock('../../api/engines/leases')
|
||||
|
||||
const client = new BaoClient('http://b', 't')
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
function setup(type: 'database' | 'ssh', kindIndex = 0) {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const onClose = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<GenerateCreds client={client} mount={`${type}/`} role="ro" kinds={ENGINES[type].roleKinds[kindIndex].creds} onClose={onClose} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return { qc, onClose, user: userEvent.setup() }
|
||||
}
|
||||
|
||||
const issued = { leaseId: 'database/creds/ro/abc', leaseDuration: 3600, renewable: true, data: { username: 'v-ro-1', password: 'hunter2' }, warnings: [] }
|
||||
|
||||
test('shows issued credentials once, and keeps them out of every cache', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
|
||||
const { qc, onClose, user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Credentials for ro' })
|
||||
expect(dialog).toHaveTextContent('v-ro-1')
|
||||
expect(dialog).toHaveTextContent('hunter2')
|
||||
expect(dialog).toHaveTextContent('valid for 3600s')
|
||||
expect(JSON.stringify(qc.getQueryCache().getAll().map((q) => q.state.data))).not.toContain('hunter2')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Done' }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(qc.getMutationCache().getAll()).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('revokes the lease on request', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
|
||||
vi.mocked(leases.revokeLease).mockResolvedValue()
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke now' }))
|
||||
expect(leases.revokeLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Lease revoked.')
|
||||
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('credentials without a lease cannot be revoked', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', leaseDuration: 0 })
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByText(/No lease/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('ssh: choose between signing and OTP, and validate inputs before calling OpenBao', async () => {
|
||||
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', data: { signed_key: 'ssh-ed25519-cert-v01@openssh.com AAAA' } })
|
||||
const { user } = setup('ssh')
|
||||
// sign is first; the public key is required
|
||||
await user.type(screen.getByLabelText(/^Public key/), ' ')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Public key is required.')
|
||||
expect(creds.generateCreds).not.toHaveBeenCalled()
|
||||
|
||||
await user.selectOptions(screen.getByLabelText('Action'), 'otp')
|
||||
await user.type(screen.getByLabelText('Target IP'), '10.0.0.5')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(creds.generateCreds).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.roleKinds[0].creds[1], 'ro', { ip: '10.0.0.5' })
|
||||
})
|
||||
|
||||
test('shows why generating failed', async () => {
|
||||
vi.mocked(creds.generateCreds).mockRejectedValue(new Error('permission denied'))
|
||||
const { user } = setup('database')
|
||||
await user.click(screen.getByRole('button', { name: 'Generate' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { generateCreds, type Credentials } from '../../api/engines/creds'
|
||||
import { revokeLease } from '../../api/engines/leases'
|
||||
import type { CredKind } from '../../api/engines/registry'
|
||||
import { emptyDraft, payloadFromDraft, type RoleDraft } from '../../api/engines/roles'
|
||||
import { RoleEditor } from './RoleEditor'
|
||||
|
||||
const show = (v: unknown) => (typeof v === 'string' ? v : JSON.stringify(v, null, 2))
|
||||
|
||||
function CopyButton({ text, label }: { text: string; label: string }) {
|
||||
return (
|
||||
<button type="button" aria-label={`Copy ${label}`} onClick={() => void navigator.clipboard?.writeText(text).catch(() => {})}>
|
||||
Copy
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks OpenBao for credentials and shows them exactly once. The result lives only in this component's mutation
|
||||
* (gcTime 0, reset on dismiss): it is never a query, so it is never cached, persisted or put in the URL.
|
||||
*/
|
||||
export function GenerateCreds({
|
||||
client,
|
||||
mount,
|
||||
role,
|
||||
kinds,
|
||||
onClose,
|
||||
}: {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
role: string
|
||||
kinds: CredKind[]
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [kindId, setKindId] = useState(kinds[0].id)
|
||||
const kind = kinds.find((k) => k.id === kindId) ?? kinds[0]
|
||||
const [draft, setDraft] = useState<RoleDraft>(() => emptyDraft({ fields: kind.inputs }))
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
|
||||
const generate = useMutation({
|
||||
gcTime: 0,
|
||||
mutationFn: (body: Record<string, unknown>) => generateCreds(client, mount, kind, role, body),
|
||||
})
|
||||
const revoke = useMutation({ gcTime: 0, mutationFn: (leaseId: string) => revokeLease(client, leaseId) })
|
||||
|
||||
const close = () => {
|
||||
generate.reset()
|
||||
revoke.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
if (generate.data) return <Issued creds={generate.data} role={role} revoke={revoke} onRevoke={() => revoke.mutate(generate.data.leaseId)} onDone={close} />
|
||||
|
||||
return (
|
||||
<div className="creds">
|
||||
{kinds.length > 1 && (
|
||||
<label>
|
||||
Action
|
||||
<select
|
||||
value={kind.id}
|
||||
onChange={(e) => {
|
||||
const next = kinds.find((k) => k.id === e.target.value) ?? kinds[0]
|
||||
setKindId(next.id)
|
||||
setDraft(emptyDraft({ fields: next.inputs }))
|
||||
setFormError(null)
|
||||
}}
|
||||
>
|
||||
{kinds.map((k) => (
|
||||
<option key={k.id} value={k.id}>
|
||||
{k.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<RoleEditor
|
||||
key={kind.id}
|
||||
kind={{ fields: kind.inputs }}
|
||||
noun={`${kind.label.toLowerCase()} for ${role}`}
|
||||
showName={false}
|
||||
submitLabel="Generate"
|
||||
draft={draft}
|
||||
pending={generate.isPending}
|
||||
error={formError ?? generate.error?.message ?? null}
|
||||
onChange={setDraft}
|
||||
onSubmit={() => {
|
||||
setFormError(null)
|
||||
try {
|
||||
generate.mutate(payloadFromDraft({ fields: kind.inputs }, draft))
|
||||
} catch (e) {
|
||||
setFormError((e as Error).message)
|
||||
}
|
||||
}}
|
||||
onCancel={close}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Issued({
|
||||
creds,
|
||||
role,
|
||||
revoke,
|
||||
onRevoke,
|
||||
onDone,
|
||||
}: {
|
||||
creds: Credentials
|
||||
role: string
|
||||
revoke: { isPending: boolean; isSuccess: boolean; error: Error | null }
|
||||
onRevoke: () => void
|
||||
onDone: () => void
|
||||
}) {
|
||||
return (
|
||||
<section role="dialog" aria-label={`Credentials for ${role}`} className="creds-issued">
|
||||
<h3>Credentials for {role}</h3>
|
||||
<p className="hint">Copy these now. They are not stored and cannot be shown again.</p>
|
||||
<dl>
|
||||
{Object.entries(creds.data).map(([k, v]) => (
|
||||
<div key={k}>
|
||||
<dt>{k}</dt>
|
||||
<dd>
|
||||
<code>{show(v)}</code> <CopyButton text={show(v)} label={k} />
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{creds.leaseId ? (
|
||||
<p>
|
||||
Lease <code>{creds.leaseId}</code>
|
||||
{creds.leaseDuration > 0 && ` · valid for ${creds.leaseDuration}s`}
|
||||
</p>
|
||||
) : (
|
||||
<p className="hint">No lease: these credentials are not revoked when they expire.</p>
|
||||
)}
|
||||
{creds.warnings.map((w) => (
|
||||
<p key={w} className="hint">
|
||||
{w}
|
||||
</p>
|
||||
))}
|
||||
{revoke.error && <p role="alert">{revoke.error.message}</p>}
|
||||
{revoke.isSuccess && <p role="status">Lease revoked.</p>}
|
||||
<div className="form-actions">
|
||||
{creds.leaseId && !revoke.isSuccess && (
|
||||
<button type="button" onClick={onRevoke} disabled={revoke.isPending}>
|
||||
Revoke now
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={onDone}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useId, type FormEvent } from 'react'
|
||||
import type { FieldDef, RoleKind } from '../../api/engines/registry'
|
||||
import type { RoleDraft } from '../../api/engines/roles'
|
||||
import type { FieldDef } from '../../api/engines/registry'
|
||||
import type { RoleDraft, Schema } from '../../api/engines/roles'
|
||||
|
||||
function Field({ field, value, onChange }: { field: FieldDef; value: string | boolean; onChange: (v: string | boolean) => void }) {
|
||||
const helpId = useId()
|
||||
@@ -19,6 +19,36 @@ function Field({ field, value, onChange }: { field: FieldDef; value: string | bo
|
||||
</label>
|
||||
)
|
||||
}
|
||||
if (field.type === 'secret') {
|
||||
const hint = 'Write-only. Leave blank to keep the stored value.'
|
||||
return (
|
||||
<label>
|
||||
{field.label}
|
||||
{field.multiline ? (
|
||||
<textarea
|
||||
value={String(value)}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
rows={4}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder={hint}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="password"
|
||||
value={String(value)}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
required={field.required}
|
||||
autoComplete="new-password"
|
||||
placeholder={hint}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
)}
|
||||
{help}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
if (field.type === 'select') {
|
||||
return (
|
||||
<label>
|
||||
@@ -65,6 +95,9 @@ function Field({ field, value, onChange }: { field: FieldDef; value: string | bo
|
||||
|
||||
export function RoleEditor({
|
||||
kind,
|
||||
noun = 'role',
|
||||
showName = true,
|
||||
submitLabel = 'Save',
|
||||
draft,
|
||||
pending,
|
||||
error,
|
||||
@@ -72,7 +105,12 @@ export function RoleEditor({
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: {
|
||||
kind: RoleKind
|
||||
kind: Schema
|
||||
/** What is being edited, for the form title: "role", "connection", ... */
|
||||
noun?: string
|
||||
/** False for single-endpoint configs that have no name. */
|
||||
showName?: boolean
|
||||
submitLabel?: string
|
||||
draft: RoleDraft
|
||||
pending: boolean
|
||||
error: string | null
|
||||
@@ -80,7 +118,7 @@ export function RoleEditor({
|
||||
onSubmit: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
const title = draft.isNew ? `New ${kind.label.toLowerCase()} role` : `Edit ${draft.name}`
|
||||
const title = draft.isNew ? `New ${noun}` : showName ? `Edit ${draft.name}` : `Edit ${noun}`
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
onSubmit()
|
||||
@@ -88,10 +126,12 @@ export function RoleEditor({
|
||||
return (
|
||||
<form onSubmit={submit} aria-label={title} className="wide">
|
||||
<h3>{title}</h3>
|
||||
<label>
|
||||
Role name
|
||||
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => onChange({ ...draft, name: e.target.value })} required />
|
||||
</label>
|
||||
{showName && (
|
||||
<label>
|
||||
{noun[0].toUpperCase() + noun.slice(1)} name
|
||||
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => onChange({ ...draft, name: e.target.value })} required />
|
||||
</label>
|
||||
)}
|
||||
{kind.fields.length === 0 ? (
|
||||
<label>
|
||||
Role (JSON)
|
||||
@@ -110,7 +150,7 @@ export function RoleEditor({
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={pending}>
|
||||
Save
|
||||
{submitLabel}
|
||||
</button>
|
||||
<button type="button" onClick={onCancel}>
|
||||
Cancel
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../../api/engines/roles'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { GenerateCreds } from './GenerateCreds'
|
||||
import { RoleEditor } from './RoleEditor'
|
||||
|
||||
export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
|
||||
@@ -23,6 +24,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
const kind = engine.roleKinds.find((k) => k.id === kindId) ?? engine.roleKinds[0]
|
||||
const [draft, setDraft] = useState<RoleDraft | null>(null)
|
||||
const [formError, setFormError] = useState<string | null>(null)
|
||||
const [credsFor, setCredsFor] = useState<string | null>(null)
|
||||
|
||||
const key = ['engine-roles', mount, kind.id]
|
||||
const roles = useQuery({ queryKey: key, queryFn: () => listRoles(client, mount, kind) })
|
||||
@@ -49,6 +51,7 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
const switchKind = (id: string) => {
|
||||
setKindId(id)
|
||||
setDraft(null)
|
||||
setCredsFor(null)
|
||||
save.reset()
|
||||
}
|
||||
|
||||
@@ -77,6 +80,11 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
<tr key={name}>
|
||||
<td>{name}</td>
|
||||
<td>
|
||||
{kind.creds.length > 0 && (
|
||||
<button type="button" aria-label={`Generate ${name}`} onClick={() => setCredsFor(name)}>
|
||||
Generate
|
||||
</button>
|
||||
)}
|
||||
<button type="button" aria-label={`Edit ${name}`} onClick={() => edit.mutate(name)}>
|
||||
Edit
|
||||
</button>
|
||||
@@ -102,6 +110,16 @@ export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{credsFor && (
|
||||
<GenerateCreds
|
||||
key={`${kind.id}/${credsFor}`}
|
||||
client={client}
|
||||
mount={mount}
|
||||
role={credsFor}
|
||||
kinds={kind.creds}
|
||||
onClose={() => setCredsFor(null)}
|
||||
/>
|
||||
)}
|
||||
{remove.error && <p role="alert">{remove.error.message}</p>}
|
||||
{edit.error && <p role="alert">{edit.error.message}</p>}
|
||||
{!draft && (
|
||||
|
||||
@@ -1453,3 +1453,35 @@ button.danger-solid:hover:not(:disabled) {
|
||||
border-radius: var(--radius);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- Dynamic engines ---------- */
|
||||
|
||||
.engine-view {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.creds-issued {
|
||||
margin: var(--s4) 0;
|
||||
padding: var(--s4);
|
||||
background: var(--surface-sunken);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.creds-issued dl {
|
||||
margin: var(--s3) 0;
|
||||
}
|
||||
|
||||
.creds-issued dt {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.creds-issued dd {
|
||||
margin: 0 0 var(--s3);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.creds-issued code {
|
||||
font-family: var(--mono);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
Reference in new issue
Block a user