Mounts: API, path validation and mountable engine types

Adds create/tune/delete for secrets engine mounts, the KV v2 settings
that live on the mount, and an impact summary for deletes. Mount lists
now carry description and explicit lease TTLs: sys/mounts/<path>/tune
reports the effective value, which would pin the system default if it
were saved back, so edits prefill from the list instead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-11-09 14:21:22 +00:00
1 parent fd20caa525
commit 66aa86028a
6 files changed
+376 -5

No files matched your search

+39
View File
@@ -347,3 +347,42 @@ export function mountKind(m: Mount): MountKind | null {
if (NOT_DYNAMIC.has(m.type)) return null
return 'dynamic'
}
/** An engine type that can be mounted from the UI, with the settings its mount form offers. */
export interface MountType {
/** Engine type for sys/mounts. */
type: string
label: string
/** Mount options, e.g. KV version 2. */
options?: Record<string, string>
/** Settings kept on the mount itself (sys/mounts). */
fields: FieldDef[]
/** KV v2 settings kept by the engine at `<mount>config`, not by sys/mounts. */
configFields: FieldDef[]
}
const DESCRIPTION: FieldDef = { key: 'description', label: 'Description', type: 'text' }
const LEASE_TTLS: FieldDef[] = [
{ key: 'default_lease_ttl', label: 'Default lease TTL', type: 'ttl', help: 'Blank uses the system default.' },
{ key: 'max_lease_ttl', label: 'Max lease TTL', type: 'ttl', help: 'Blank uses the system default.' },
]
export const MOUNT_TYPES: MountType[] = [
{
type: 'kv',
label: 'KV v2',
options: { version: '2' },
fields: [DESCRIPTION],
configFields: [
{ key: 'max_versions', label: 'Max versions', type: 'text', help: 'Versions kept per secret. 0 keeps the system default.' },
{ key: 'cas_required', label: 'Require check-and-set on writes', type: 'bool' },
{ key: 'delete_version_after', label: 'Delete versions after', type: 'ttl', help: 'Blank never deletes them.' },
],
},
{ type: 'database', label: 'Database', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
{ type: 'aws', label: 'AWS', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
{ type: 'ssh', label: 'SSH', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
]
/** The mount form for a mounted engine, or null for one the UI can't create (it can still delete it). */
export const mountTypeFor = (m: Pick<Mount, 'type'>): MountType | null => MOUNT_TYPES.find((t) => t.type === m.type) ?? null
+101
View File
@@ -0,0 +1,101 @@
import { expect, test, vi } from 'vitest'
import { BaoClient } from './bao'
import { MOUNT_TYPES, mountTypeFor } from './engines/registry'
import * as leases from './engines/leases'
import * as roles from './engines/roles'
import { createMount, deleteMount, mountImpact, PartialMountError, readKvConfig, tuneMount } from './mounts'
import * as secrets from './secrets'
const kv = MOUNT_TYPES.find((t) => t.type === 'kv')!
const ssh = MOUNT_TYPES.find((t) => t.type === 'ssh')!
const client = () => new BaoClient('http://b', 't')
test('knows which engines it can mount', () => {
expect(MOUNT_TYPES.map((t) => t.type)).toEqual(['kv', 'database', 'aws', 'ssh'])
expect(mountTypeFor({ type: 'ssh' })).toBe(ssh)
expect(mountTypeFor({ type: 'pki' })).toBeNull()
})
test('creates a dynamic mount with its lease TTLs, leaving them out when blank', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await createMount(c, 'my-ssh', ssh, { description: 'hosts', default_lease_ttl: '1h', max_lease_ttl: '8h' })
expect(req).toHaveBeenCalledWith('POST', 'sys/mounts/my-ssh', {
type: 'ssh',
description: 'hosts',
config: { default_lease_ttl: '1h', max_lease_ttl: '8h' },
})
await createMount(c, 'plain/', ssh, {})
expect(req).toHaveBeenLastCalledWith('POST', 'sys/mounts/plain', { type: 'ssh', description: '' })
})
test('creating KV v2 mounts version 2, then saves the KV settings on the mount', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await createMount(c, 'team/store', kv, { description: 'd', max_versions: '5', cas_required: true, delete_version_after: '720h' })
expect(req).toHaveBeenNthCalledWith(1, 'POST', 'sys/mounts/team/store', { type: 'kv', description: 'd', options: { version: '2' } })
expect(req).toHaveBeenNthCalledWith(2, 'POST', 'team/store/config', { max_versions: 5, cas_required: true, delete_version_after: '720h' })
})
test('if saving KV settings fails the error says the mount exists', async () => {
const c = client()
vi.spyOn(c, 'request').mockImplementation(async (_m, path) => {
if (path.endsWith('/config')) throw new Error('permission denied')
})
const err = await createMount(c, 'store', kv, { cas_required: true }).catch((e: unknown) => e)
expect(err).toBeInstanceOf(PartialMountError)
expect((err as Error).message).toBe('store/ was mounted, but saving its KV settings failed: permission denied')
})
test('a failed mount does not try the KV settings', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockRejectedValue(new Error('path is already in use'))
await expect(createMount(c, 'store', kv, { cas_required: true })).rejects.toThrow('already in use')
expect(req).toHaveBeenCalledTimes(1)
})
test('tuning sends 0 for a blank TTL so it resets to the system default', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await tuneMount(c, 'database/', MOUNT_TYPES[1], { description: 'x', default_lease_ttl: '2h' })
expect(req).toHaveBeenCalledWith('POST', 'sys/mounts/database/tune', { description: 'x', default_lease_ttl: '2h', max_lease_ttl: '0' })
})
test('tuning KV updates the description and the KV settings, with no TTLs', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await tuneMount(c, 'secret/', kv, { description: 'kv', max_versions: '10', cas_required: false })
expect(req).toHaveBeenNthCalledWith(1, 'POST', 'sys/mounts/secret/tune', { description: 'kv' })
expect(req).toHaveBeenNthCalledWith(2, 'POST', 'secret/config', { max_versions: 10, cas_required: false })
})
test('delete and KV config read use the mount path', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue({ data: { max_versions: 3 } })
await deleteMount(c, 'team/store/')
expect(req).toHaveBeenCalledWith('DELETE', 'sys/mounts/team/store')
expect(await readKvConfig(c, 'team/store')).toEqual({ max_versions: 3 })
expect(req).toHaveBeenLastCalledWith('GET', 'team/store/config')
})
test('impact of deleting a KV mount counts top-level entries', async () => {
vi.spyOn(secrets, 'listSecrets').mockResolvedValue([
{ name: 'a/', path: 'a/', isFolder: true },
{ name: 'b', path: 'b', isFolder: false },
])
expect(await mountImpact(client(), 'secret/', 'kv')).toEqual({ kind: 'kv', topLevelEntries: 2, unknown: [] })
})
test('impact of deleting a dynamic mount counts roles and notes leases', async () => {
vi.spyOn(roles, 'listRoles').mockImplementation(async (_c, _m, kind) => (kind.id === 'roles' ? ['ro', 'rw'] : ['svc']))
vi.spyOn(leases, 'listLeases').mockResolvedValue([{ name: 'creds/', path: 'database/creds/', isFolder: true }])
expect(await mountImpact(client(), 'database/', 'database')).toEqual({ kind: 'dynamic', roles: 3, hasLeases: true, unknown: [] })
})
test('impact reports what it was not allowed to count', async () => {
vi.spyOn(roles, 'listRoles').mockResolvedValue(['ro'])
vi.spyOn(leases, 'listLeases').mockRejectedValue(new Error('permission denied'))
expect(await mountImpact(client(), 'ssh/', 'ssh')).toEqual({ kind: 'dynamic', roles: 1, hasLeases: undefined, unknown: ['leases'] })
vi.spyOn(secrets, 'listSecrets').mockRejectedValue(new Error('permission denied'))
expect(await mountImpact(client(), 'secret/', 'kv')).toEqual({ kind: 'kv', topLevelEntries: undefined, unknown: ['secrets'] })
})
+126
View File
@@ -0,0 +1,126 @@
import type { BaoClient } from './bao'
import { engineFor, type MountType } from './engines/registry'
import { listLeases } from './engines/leases'
import { listRoles, type RoleData } from './engines/roles'
import { listSecrets } from './secrets'
const encPath = (mount: string) =>
mount
.replace(/^\/+|\/+$/g, '')
.split('/')
.map(encodeURIComponent)
.join('/')
const sysPath = (mount: string) => `sys/mounts/${encPath(mount)}`
const withSlash = (mount: string) => (mount.endsWith('/') ? mount : `${mount}/`)
/** Thrown when the mount was created but a follow-up step failed, so the caller can say the mount exists. */
export class PartialMountError extends Error {
constructor(message: string) {
super(message)
this.name = 'PartialMountError'
}
}
/** Splits form values into what sys/mounts takes and what the KV engine keeps itself. */
function split(type: MountType, body: RoleData): { sys: RoleData; kv: RoleData } {
const configKeys = new Set(type.configFields.map((f) => f.key))
const sys: RoleData = {}
const kv: RoleData = {}
for (const [k, v] of Object.entries(body)) (configKeys.has(k) ? kv : sys)[k] = v
return { sys, kv }
}
/** KV v2 sends max_versions as a number; everything else stays as the form produced it. */
function kvBody(kv: RoleData): RoleData {
const out = { ...kv }
if (typeof out.max_versions === 'string') out.max_versions = Number(out.max_versions)
return out
}
/** Mounts a secrets engine at `path`. KV v2 settings take a second call; if it fails the mount is still there. */
export async function createMount(c: BaoClient, path: string, type: MountType, body: RoleData): Promise<void> {
const { sys, kv } = split(type, body)
const config: RoleData = {}
if (sys.default_lease_ttl) config.default_lease_ttl = sys.default_lease_ttl
if (sys.max_lease_ttl) config.max_lease_ttl = sys.max_lease_ttl
await c.request('POST', sysPath(path), {
type: type.type,
description: sys.description ?? '',
...(type.options ? { options: type.options } : {}),
...(Object.keys(config).length ? { config } : {}),
})
if (Object.keys(kv).length) {
try {
await writeKvConfig(c, path, type, kv)
} catch (e) {
throw new PartialMountError(`${withSlash(path)} was mounted, but saving its KV settings failed: ${(e as Error).message}`)
}
}
}
/**
* Changes a mount's description and default/max lease TTL (and KV settings). Path and type can't change. A blank TTL
* resets to the system default, which OpenBao spells 0.
*/
export async function tuneMount(c: BaoClient, path: string, type: MountType, body: RoleData): Promise<void> {
const { sys, kv } = split(type, body)
const hasTtl = type.fields.some((f) => f.key === 'default_lease_ttl')
await c.request('POST', `${sysPath(path)}/tune`, {
description: sys.description ?? '',
...(hasTtl ? { default_lease_ttl: sys.default_lease_ttl ?? '0', max_lease_ttl: sys.max_lease_ttl ?? '0' } : {}),
})
if (Object.keys(kv).length) await writeKvConfig(c, path, type, kv)
}
/** Unmounts the engine. This permanently deletes everything stored in it and revokes every lease it issued. */
export async function deleteMount(c: BaoClient, path: string): Promise<void> {
await c.request('DELETE', sysPath(path))
}
export async function readKvConfig(c: BaoClient, mount: string): Promise<RoleData> {
const res = await c.request<{ data: RoleData }>('GET', `${withSlash(mount)}config`)
return res.data
}
async function writeKvConfig(c: BaoClient, mount: string, type: MountType, kv: RoleData): Promise<void> {
if (type.configFields.length === 0) return
await c.request('POST', `${withSlash(mount)}config`, kvBody(kv))
}
export interface MountImpact {
kind: 'kv' | 'dynamic'
/** KV: entries at the top level of the mount (folders count as one). */
topLevelEntries?: number
/** Dynamic: roles across all role kinds. */
roles?: number
/** Dynamic: whether any lease exists under the mount (they are all revoked on delete). */
hasLeases?: boolean
/** Things that could not be counted, e.g. no permission to list. */
unknown: string[]
}
/** What deleting a mount would destroy, as far as the token can see. Never reads secret values. */
export async function mountImpact(c: BaoClient, mount: string, type: string): Promise<MountImpact> {
const unknown: string[] = []
if (type === 'kv') {
const entries = await listSecrets(c, mount, '').catch(() => {
unknown.push('secrets')
return null
})
return { kind: 'kv', topLevelEntries: entries?.length, unknown }
}
const engine = engineFor(type)
let roles = 0
for (const kind of engine.roleKinds) {
roles += (await listRoles(c, mount, kind).catch(() => {
unknown.push(kind.label.toLowerCase())
return []
})).length
}
const leases = await listLeases(c, mount).catch(() => {
unknown.push('leases')
return null
})
return { kind: 'dynamic', roles, hasLeases: leases === null ? undefined : leases.length > 0, unknown }
}
+26 -5
View File
@@ -21,16 +21,37 @@ export interface Mount {
type: string
/** KV version ("1" | "2") when the engine is KV. */
version?: string
description?: string
/**
* Seconds explicitly set on this mount, 0 when it uses the system default. (sys/mounts/<path>/tune reports the
* effective value instead, which would pin the default if it were saved back.)
*/
defaultLeaseTtl?: number
maxLeaseTtl?: number
}
/** Every secrets engine mount visible to the token, sorted by path. */
export async function listMounts(c: BaoClient): Promise<Mount[]> {
const res = await c.request<{ data: Record<string, { type: string; options?: { version?: string } | null }> }>(
'GET',
'sys/mounts',
)
const res = await c.request<{
data: Record<
string,
{
type: string
description?: string
options?: { version?: string } | null
config?: { default_lease_ttl?: number; max_lease_ttl?: number }
}
>
}>('GET', 'sys/mounts')
return Object.entries(res.data)
.map(([path, m]) => ({ path, type: m.type, version: m.options?.version }))
.map(([path, m]) => ({
path,
type: m.type,
version: m.options?.version,
description: m.description,
defaultLeaseTtl: m.config?.default_lease_ttl,
maxLeaseTtl: m.config?.max_lease_ttl,
}))
.sort((a, b) => a.path.localeCompare(b.path))
}
+40
View File
@@ -0,0 +1,40 @@
import { expect, test } from 'vitest'
import { policiesReferencing, validateMountPath } from './mounts'
const existing = ['secret/', 'database/', 'team/kv/']
test('accepts ordinary and nested paths, with or without slashes', () => {
for (const p of ['scratch', 'my-store_2', 'scratch/', 'apps/payments', '9lives']) expect(validateMountPath(p, existing), p).toBeNull()
})
test('rejects empty, oddly-formed and uppercase paths', () => {
expect(validateMountPath('', existing)).toBe('Path is required.')
expect(validateMountPath('/', existing)).toBe('Path is required.')
expect(validateMountPath(' x', existing)).toMatch(/spaces/)
for (const p of ['My Store', 'Upper', 'a//b', '-lead', 'dot.ted', 'a/_b', 'ünï']) expect(validateMountPath(p, existing), p).toMatch(/lowercase/)
})
test('rejects the names OpenBao reserves, also as a prefix', () => {
for (const p of ['sys', 'auth', 'identity', 'cubbyhole', 'sys/x', 'auth/kv']) expect(validateMountPath(p, existing), p).toMatch(/reserved/)
})
test('rejects a path equal to, inside or containing an existing mount', () => {
expect(validateMountPath('secret', existing)).toMatch(/already a secrets engine/)
expect(validateMountPath('secret/', existing)).toMatch(/already/)
expect(validateMountPath('secret/inner', existing)).toMatch(/inside the existing mount "secret\/"/)
expect(validateMountPath('team', existing)).toMatch(/contain the existing mount "team\/kv\/"/)
expect(validateMountPath('secrets', existing)).toBeNull() // shares a prefix, not a path segment
})
test('finds policies with rules under a mount, however the mount is written', () => {
const policies = [
{ name: 'b-uses', hcl: 'path "secret/data/app/*" { capabilities = ["read"] }' },
{ name: 'a-uses', hcl: 'path "secret/metadata/*" { capabilities = ["list"] }\npath "x/y" { capabilities = ["read"] }' },
{ name: 'other', hcl: 'path "secrets/data/x" { capabilities = ["read"] }' },
{ name: 'unreadable', hcl: null },
{ name: 'broken', hcl: 'path "secret/x" {' },
]
expect(policiesReferencing(policies, 'secret/')).toEqual(['a-uses', 'b-uses'])
expect(policiesReferencing(policies, 'secret')).toEqual(['a-uses', 'b-uses'])
expect(policiesReferencing(policies, 'nothing/')).toEqual([])
})
+44
View File
@@ -0,0 +1,44 @@
import { parsePolicy } from './policy'
/** Prefixes OpenBao reserves for itself; a secrets engine cannot be mounted at or under them. */
const RESERVED = ['sys', 'auth', 'identity', 'cubbyhole']
const SEGMENT = /^[a-z0-9][a-z0-9_-]*$/
const norm = (p: string) => p.replace(/^\/+|\/+$/g, '')
/**
* Error message for a mount path that can't be used, or null. `existing` are the current mounts (with or without
* trailing slashes). Nested paths such as "team/kv" are fine, but a mount can't sit inside another or contain one.
*/
export function validateMountPath(path: string, existing: string[]): string | null {
const p = norm(path)
if (!p) return 'Path is required.'
if (path !== path.trim()) return 'Path must not start or end with spaces.'
if (!p.split('/').every((s) => SEGMENT.test(s))) {
return 'Use lowercase letters, digits, "-" and "_", starting each part with a letter or digit. Parts are separated by "/".'
}
const first = p.split('/')[0]
if (RESERVED.includes(first)) return `"${first}" is reserved by OpenBao.`
for (const e of existing.map(norm)) {
if (e === p) return `"${p}/" is already a secrets engine.`
if (p.startsWith(`${e}/`)) return `"${p}/" would sit inside the existing mount "${e}/".`
if (e.startsWith(`${p}/`)) return `"${p}/" would contain the existing mount "${e}/".`
}
return null
}
export interface PolicyText {
name: string
/** Null when the policy could not be read. */
hcl: string | null
}
/** Policies with a rule on a path under `mount`, which would be left pointing at nothing if it were deleted. */
export function policiesReferencing(policies: PolicyText[], mount: string): string[] {
const m = mount.endsWith('/') ? mount : `${mount}/`
return policies
.filter((p) => p.hcl !== null && parsePolicy(p.hcl).rules.some((r) => r.path.startsWith(m)))
.map((p) => p.name)
.sort((a, b) => a.localeCompare(b))
}