Secrets: browse, renew and revoke leases for dynamic engines
Adds a Leases tab that walks sys/leases/lookup under the mount, shows a lease's timings on demand, renews renewable leases, and revokes one lease or everything under a prefix after confirmation. Covered by unit tests and an ssh OTP integration test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
48746e2150
commit
48ee757e8d
7 files changed
+362
-11
No files matched your search
@@ -2,7 +2,6 @@ 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'
|
||||
|
||||
@@ -74,10 +73,3 @@ test('credential requests: POST sends inputs, result is normalised', async () =>
|
||||
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,50 @@
|
||||
import { expect, test, vi } from 'vitest'
|
||||
import { BaoClient } from '../bao'
|
||||
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases'
|
||||
|
||||
const c = () => new BaoClient('http://b', 't')
|
||||
|
||||
test('lists folders before lease ids, joining them onto the prefix', async () => {
|
||||
const client = c()
|
||||
const list = vi.spyOn(client, 'list').mockResolvedValue(['zz9', 'ro/', 'aa1'])
|
||||
expect(await listLeases(client, 'database/creds/')).toEqual([
|
||||
{ name: 'ro/', path: 'database/creds/ro/', isFolder: true },
|
||||
{ name: 'aa1', path: 'database/creds/aa1', isFolder: false },
|
||||
{ name: 'zz9', path: 'database/creds/zz9', isFolder: false },
|
||||
])
|
||||
expect(list).toHaveBeenCalledWith('sys/leases/lookup/database/creds/')
|
||||
})
|
||||
|
||||
test('looks up a lease and maps its fields', async () => {
|
||||
const client = c()
|
||||
const req = vi.spyOn(client, 'request').mockResolvedValue({
|
||||
data: { id: 'database/creds/ro/abc', issue_time: '2026-01-01T00:00:00Z', expire_time: null, last_renewal: null, renewable: true, ttl: 120 },
|
||||
})
|
||||
expect(await lookupLease(client, 'database/creds/ro/abc')).toEqual({
|
||||
id: 'database/creds/ro/abc',
|
||||
issueTime: '2026-01-01T00:00:00Z',
|
||||
expireTime: null,
|
||||
lastRenewal: null,
|
||||
renewable: true,
|
||||
ttl: 120,
|
||||
})
|
||||
expect(req).toHaveBeenCalledWith('PUT', 'sys/leases/lookup', { lease_id: 'database/creds/ro/abc' })
|
||||
})
|
||||
|
||||
test('renew sends an increment only when given and returns the granted duration', async () => {
|
||||
const client = c()
|
||||
const req = vi.spyOn(client, 'request').mockResolvedValue({ lease_duration: 300 })
|
||||
expect(await renewLease(client, 'a/b')).toBe(300)
|
||||
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/renew', { lease_id: 'a/b' })
|
||||
await renewLease(client, 'a/b', '1h')
|
||||
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/renew', { lease_id: 'a/b', increment: '1h' })
|
||||
})
|
||||
|
||||
test('revoke and revoke-prefix', async () => {
|
||||
const client = c()
|
||||
const req = vi.spyOn(client, 'request').mockResolvedValue(undefined)
|
||||
await revokeLease(client, 'database/creds/ro/xyz')
|
||||
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/revoke', { lease_id: 'database/creds/ro/xyz' })
|
||||
await revokePrefix(client, 'database/creds/ro/')
|
||||
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/revoke-prefix/database/creds/ro', {})
|
||||
})
|
||||
@@ -1,6 +1,59 @@
|
||||
import type { BaoClient } from '../bao'
|
||||
|
||||
const enc = (path: string) => path.split('/').map(encodeURIComponent).join('/')
|
||||
|
||||
export interface LeaseEntry {
|
||||
name: string
|
||||
/** Full lease id, or for folders the prefix (trailing slash) to browse next. */
|
||||
path: string
|
||||
isFolder: boolean
|
||||
}
|
||||
|
||||
export interface LeaseInfo {
|
||||
id: string
|
||||
/** ISO timestamps; expireTime is null for leases that never expire. */
|
||||
issueTime: string
|
||||
expireTime: string | null
|
||||
lastRenewal: string | null
|
||||
renewable: boolean
|
||||
/** Seconds remaining. */
|
||||
ttl: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists leases under a prefix such as "database/creds/" (the mount plus a path). Folders end with "/" and the rest are
|
||||
* lease ids. Needs sudo on sys/leases/lookup, which most tokens lack.
|
||||
*/
|
||||
export async function listLeases(c: BaoClient, prefix: string): Promise<LeaseEntry[]> {
|
||||
const keys = await c.list(`sys/leases/lookup/${enc(prefix)}`)
|
||||
return keys
|
||||
.map((k) => ({ name: k, path: prefix + k, isFolder: k.endsWith('/') }))
|
||||
.sort((a, b) => Number(b.isFolder) - Number(a.isFolder) || a.name.localeCompare(b.name))
|
||||
}
|
||||
|
||||
export async function lookupLease(c: BaoClient, leaseId: string): Promise<LeaseInfo> {
|
||||
const res = await c.request<{
|
||||
data: { id: string; issue_time: string; expire_time: string | null; last_renewal: string | null; renewable: boolean; ttl: number }
|
||||
}>('PUT', 'sys/leases/lookup', { lease_id: leaseId })
|
||||
const d = res.data
|
||||
return { id: d.id, issueTime: d.issue_time, expireTime: d.expire_time, lastRenewal: d.last_renewal, renewable: d.renewable, ttl: d.ttl }
|
||||
}
|
||||
|
||||
/** Extends a lease by `increment` (e.g. "1h"); OpenBao may grant less. Returns the new lease duration in seconds. */
|
||||
export async function renewLease(c: BaoClient, leaseId: string, increment?: string): Promise<number> {
|
||||
const res = await c.request<{ lease_duration: number }>('PUT', 'sys/leases/renew', {
|
||||
lease_id: leaseId,
|
||||
...(increment ? { increment } : {}),
|
||||
})
|
||||
return res.lease_duration
|
||||
}
|
||||
|
||||
/** 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 })
|
||||
}
|
||||
|
||||
/** Revokes every lease under a prefix, e.g. all credentials issued from one role. Needs sudo. */
|
||||
export async function revokePrefix(c: BaoClient, prefix: string): Promise<void> {
|
||||
await c.request('PUT', `sys/leases/revoke-prefix/${enc(prefix.replace(/\/+$/, ''))}`, {})
|
||||
}
|
||||
@@ -2,7 +2,7 @@ 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 { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases'
|
||||
import { listMounts } from '../secrets'
|
||||
import { ENGINES } from './registry'
|
||||
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
|
||||
@@ -99,6 +99,26 @@ describe('dynamic engine config and credentials', () => {
|
||||
await revokeLease(client, out.leaseId)
|
||||
})
|
||||
|
||||
test('leases can be browsed, inspected, renewed and revoked by prefix', async () => {
|
||||
const a = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.3' })
|
||||
const b = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.4' })
|
||||
|
||||
// folders first: mount -> creds/ -> otp/ -> lease ids
|
||||
expect(await listLeases(client, mount)).toContainEqual({ name: 'creds/', path: `${mount}creds/`, isFolder: true })
|
||||
const ids = (await listLeases(client, `${mount}creds/otp/`)).map((e) => e.path)
|
||||
expect(ids).toEqual(expect.arrayContaining([a.leaseId, b.leaseId]))
|
||||
|
||||
const info = await lookupLease(client, a.leaseId)
|
||||
expect(info.id).toBe(a.leaseId)
|
||||
expect(info.ttl).toBeGreaterThan(0)
|
||||
expect(info.renewable).toBe(false)
|
||||
// OTP leases are not renewable, and the UI only offers Renew when renewable; OpenBao says so itself
|
||||
await expect(renewLease(client, a.leaseId)).rejects.toThrow()
|
||||
|
||||
await revokePrefix(client, `${mount}creds/otp/`)
|
||||
expect(await listLeases(client, `${mount}creds/otp/`)).toEqual([])
|
||||
})
|
||||
|
||||
test('single-endpoint config round-trips (aws lease)', async (ctx) => {
|
||||
if (!awsAvailable) ctx.skip()
|
||||
const lease = ENGINES.aws.configs[1]
|
||||
|
||||
@@ -3,16 +3,18 @@ import type { BaoClient } from '../../api/bao'
|
||||
import { engineFor } from '../../api/engines/registry'
|
||||
import type { Mount } from '../../api/secrets'
|
||||
import { ConfigPanel } from './ConfigPanel'
|
||||
import { LeasesPanel } from './LeasesPanel'
|
||||
import { RolesPanel } from './RolesPanel'
|
||||
|
||||
type Tab = 'roles' | 'config'
|
||||
type Tab = 'roles' | 'config' | 'leases'
|
||||
|
||||
/** Roles and Config (and, in a later phase, Leases) for a dynamic secrets engine. */
|
||||
/** Roles, Config and 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' })
|
||||
tabs.push({ id: 'leases', label: 'Leases' })
|
||||
const current = tabs.some((t) => t.id === tab) ? tab : 'roles'
|
||||
|
||||
return (
|
||||
@@ -30,6 +32,7 @@ export function EngineView({ client, mount }: { client: BaoClient; mount: Mount
|
||||
</div>
|
||||
)}
|
||||
{current === 'roles' && <RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
{current === 'leases' && <LeasesPanel key={mount.path} client={client} mount={mount.path} />}
|
||||
{current === 'config' && <ConfigPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, within } 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 leases from '../../api/engines/leases'
|
||||
import { LeasesPanel } from './LeasesPanel'
|
||||
|
||||
vi.mock('../../api/engines/leases')
|
||||
|
||||
const client = new BaoClient('http://b', 't')
|
||||
|
||||
function setup() {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<LeasesPanel client={client} mount="database/" />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return userEvent.setup()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(leases.listLeases).mockImplementation(async (_c, prefix) =>
|
||||
prefix === 'database/'
|
||||
? [{ name: 'creds/', path: 'database/creds/', isFolder: true }]
|
||||
: prefix === 'database/creds/'
|
||||
? [{ name: 'ro/', path: 'database/creds/ro/', isFolder: true }]
|
||||
: [{ name: 'abc', path: 'database/creds/ro/abc', isFolder: false }],
|
||||
)
|
||||
vi.mocked(leases.lookupLease).mockResolvedValue({
|
||||
id: 'database/creds/ro/abc',
|
||||
issueTime: '2026-01-01T00:00:00Z',
|
||||
expireTime: '2026-01-01T01:00:00Z',
|
||||
lastRenewal: null,
|
||||
renewable: true,
|
||||
ttl: 3000,
|
||||
})
|
||||
})
|
||||
afterEach(() => vi.resetAllMocks())
|
||||
|
||||
async function openLease(user: ReturnType<typeof userEvent.setup>) {
|
||||
await user.click(await screen.findByRole('button', { name: /creds\// }))
|
||||
await user.click(await screen.findByRole('button', { name: /ro\// }))
|
||||
}
|
||||
|
||||
test('browses folders down to a lease and shows its details', async () => {
|
||||
const user = setup()
|
||||
await openLease(user)
|
||||
await user.click(await screen.findByRole('button', { name: 'Details abc' }))
|
||||
const details = await screen.findByLabelText('Lease abc')
|
||||
expect(within(details).getByText('3000s')).toBeInTheDocument()
|
||||
expect(leases.lookupLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
|
||||
})
|
||||
|
||||
test('renews a renewable lease', async () => {
|
||||
vi.mocked(leases.renewLease).mockResolvedValue(3600)
|
||||
const user = setup()
|
||||
await openLease(user)
|
||||
await user.click(await screen.findByRole('button', { name: 'Details abc' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Renew' }))
|
||||
expect(leases.renewLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
|
||||
})
|
||||
|
||||
test('revokes one lease only after confirmation', async () => {
|
||||
vi.mocked(leases.revokeLease).mockResolvedValue()
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
|
||||
const user = setup()
|
||||
await openLease(user)
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke abc' }))
|
||||
expect(leases.revokeLease).not.toHaveBeenCalled()
|
||||
confirm.mockReturnValue(true)
|
||||
await user.click(screen.getByRole('button', { name: 'Revoke abc' }))
|
||||
expect(leases.revokeLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
|
||||
})
|
||||
|
||||
test('revoke-all is offered below the mount root and names the prefix', async () => {
|
||||
vi.mocked(leases.revokePrefix).mockResolvedValue()
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(true)
|
||||
const user = setup()
|
||||
await screen.findByRole('button', { name: /creds\// })
|
||||
expect(screen.queryByRole('button', { name: /Revoke all/ })).not.toBeInTheDocument()
|
||||
|
||||
await openLease(user)
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke all under this prefix' }))
|
||||
expect(confirm.mock.calls[0][0]).toContain('database/creds/ro/')
|
||||
expect(leases.revokePrefix).toHaveBeenCalledWith(client, 'database/creds/ro/')
|
||||
})
|
||||
|
||||
test('says so when there are no leases, and why listing failed', async () => {
|
||||
vi.mocked(leases.listLeases).mockResolvedValueOnce([])
|
||||
setup()
|
||||
expect(await screen.findByText('No leases under database/.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('shows the error when listing is not permitted', async () => {
|
||||
vi.mocked(leases.listLeases).mockRejectedValue(new Error('permission denied'))
|
||||
setup()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from '../../api/engines/leases'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : 'never')
|
||||
|
||||
function LeaseRow({ client, id, name, onChanged }: { client: BaoClient; id: string; name: string; onChanged: () => void }) {
|
||||
const confirm = useConfirm()
|
||||
const [open, setOpen] = useState(false)
|
||||
const info = useQuery({ queryKey: ['lease', id], queryFn: () => lookupLease(client, id), enabled: open, retry: false })
|
||||
const renew = useMutation({
|
||||
mutationFn: () => renewLease(client, id),
|
||||
onSuccess: () => info.refetch(),
|
||||
})
|
||||
const revoke = useMutation({ mutationFn: () => revokeLease(client, id), onSuccess: onChanged })
|
||||
|
||||
return (
|
||||
<li>
|
||||
<span>{name}</span>
|
||||
<button type="button" aria-expanded={open} aria-label={`Details ${name}`} onClick={() => setOpen(!open)}>
|
||||
Details
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Revoke ${name}`}
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: 'Revoke this lease?', message: 'The credentials it issued stop working immediately.', confirmLabel: 'Revoke' }))
|
||||
revoke.mutate()
|
||||
}}
|
||||
>
|
||||
Revoke
|
||||
</button>
|
||||
{open && info.isPending && <p role="status">Loading…</p>}
|
||||
{open && info.error && <p role="alert">{info.error.message}</p>}
|
||||
{open && info.data && (
|
||||
<dl aria-label={`Lease ${name}`}>
|
||||
<dt>Issued</dt>
|
||||
<dd>{when(info.data.issueTime)}</dd>
|
||||
<dt>Expires</dt>
|
||||
<dd>{when(info.data.expireTime)}</dd>
|
||||
<dt>Remaining</dt>
|
||||
<dd>{info.data.ttl}s</dd>
|
||||
{info.data.lastRenewal && (
|
||||
<>
|
||||
<dt>Last renewed</dt>
|
||||
<dd>{when(info.data.lastRenewal)}</dd>
|
||||
</>
|
||||
)}
|
||||
{info.data.renewable && (
|
||||
<dd>
|
||||
<button type="button" onClick={() => renew.mutate()} disabled={renew.isPending}>
|
||||
Renew
|
||||
</button>
|
||||
</dd>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
{renew.error && <p role="alert">{renew.error.message}</p>}
|
||||
{revoke.error && <p role="alert">{revoke.error.message}</p>}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** Browse and revoke the leases issued by a dynamic engine mount. */
|
||||
export function LeasesPanel({ client, mount }: { client: BaoClient; mount: string }) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const [prefix, setPrefix] = useState(mount)
|
||||
|
||||
const key = ['leases', mount, prefix]
|
||||
const entries = useQuery({ queryKey: key, queryFn: () => listLeases(client, prefix), retry: false })
|
||||
const refresh = () => qc.invalidateQueries({ queryKey: ['leases', mount] })
|
||||
const revokeAll = useMutation({
|
||||
mutationFn: () => revokePrefix(client, prefix),
|
||||
onSuccess: refresh,
|
||||
})
|
||||
|
||||
const crumbs = prefix.slice(mount.length).split('/').filter(Boolean)
|
||||
const atRoot = prefix === mount
|
||||
|
||||
return (
|
||||
<section aria-label="Leases">
|
||||
<nav aria-label="Lease path" className="crumbs">
|
||||
<button type="button" onClick={() => setPrefix(mount)}>
|
||||
{mount}
|
||||
</button>
|
||||
{crumbs.map((c, i) => (
|
||||
<button key={i} type="button" onClick={() => setPrefix(mount + crumbs.slice(0, i + 1).join('/') + '/')}>
|
||||
{c}/
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<ListState query={entries} empty={`No leases under ${prefix}.`} />
|
||||
{!!entries.data?.length && (
|
||||
<ul className="entries" aria-label={`Leases under ${prefix}`}>
|
||||
{entries.data.map((e) =>
|
||||
e.isFolder ? (
|
||||
<li key={e.path}>
|
||||
<button type="button" className="entry-folder" onClick={() => setPrefix(e.path)}>
|
||||
{e.name}
|
||||
<span aria-hidden="true">›</span>
|
||||
</button>
|
||||
</li>
|
||||
) : (
|
||||
<LeaseRow key={e.path} client={client} id={e.path} name={e.name} onChanged={refresh} />
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
{!atRoot && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: `Revoke every lease under ${prefix}?`,
|
||||
message: 'All credentials issued under this prefix stop working immediately. This cannot be undone.',
|
||||
confirmLabel: 'Revoke all',
|
||||
})
|
||||
)
|
||||
revokeAll.mutate()
|
||||
}}
|
||||
disabled={revokeAll.isPending}
|
||||
>
|
||||
Revoke all under this prefix
|
||||
</button>
|
||||
)}
|
||||
{revokeAll.error && <p role="alert">{revokeAll.error.message}</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user