diff --git a/src/api/engines/config.test.ts b/src/api/engines/config.test.ts index 72e6e54..961d1a4 100644 --- a/src/api/engines/config.test.ts +++ b/src/api/engines/config.test.ts @@ -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' }) -}) diff --git a/src/api/engines/leases.test.ts b/src/api/engines/leases.test.ts new file mode 100644 index 0000000..9634c3e --- /dev/null +++ b/src/api/engines/leases.test.ts @@ -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', {}) +}) diff --git a/src/api/engines/leases.ts b/src/api/engines/leases.ts index cf62272..8d9794c 100644 --- a/src/api/engines/leases.ts +++ b/src/api/engines/leases.ts @@ -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 { + 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 { + 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 { + 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 { 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 { + await c.request('PUT', `sys/leases/revoke-prefix/${enc(prefix.replace(/\/+$/, ''))}`, {}) +} diff --git a/src/api/engines/roles.integration.test.ts b/src/api/engines/roles.integration.test.ts index bc528a3..75d85ea 100644 --- a/src/api/engines/roles.integration.test.ts +++ b/src/api/engines/roles.integration.test.ts @@ -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] diff --git a/src/features/secrets/EngineView.tsx b/src/features/secrets/EngineView.tsx index 0b8e7cb..14c1c0b 100644 --- a/src/features/secrets/EngineView.tsx +++ b/src/features/secrets/EngineView.tsx @@ -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('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 )} {current === 'roles' && } + {current === 'leases' && } {current === 'config' && } ) diff --git a/src/features/secrets/LeasesPanel.test.tsx b/src/features/secrets/LeasesPanel.test.tsx new file mode 100644 index 0000000..1044d24 --- /dev/null +++ b/src/features/secrets/LeasesPanel.test.tsx @@ -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( + + + , + ) + 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) { + 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') +}) diff --git a/src/features/secrets/LeasesPanel.tsx b/src/features/secrets/LeasesPanel.tsx new file mode 100644 index 0000000..132ea5b --- /dev/null +++ b/src/features/secrets/LeasesPanel.tsx @@ -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 ( +
  • + {name} + + + {open && info.isPending &&

    Loading…

    } + {open && info.error &&

    {info.error.message}

    } + {open && info.data && ( +
    +
    Issued
    +
    {when(info.data.issueTime)}
    +
    Expires
    +
    {when(info.data.expireTime)}
    +
    Remaining
    +
    {info.data.ttl}s
    + {info.data.lastRenewal && ( + <> +
    Last renewed
    +
    {when(info.data.lastRenewal)}
    + + )} + {info.data.renewable && ( +
    + +
    + )} +
    + )} + {renew.error &&

    {renew.error.message}

    } + {revoke.error &&

    {revoke.error.message}

    } +
  • + ) +} + +/** 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 ( +
    + + + {!!entries.data?.length && ( +
      + {entries.data.map((e) => + e.isFolder ? ( +
    • + +
    • + ) : ( + + ), + )} +
    + )} + {!atRoot && ( + + )} + {revokeAll.error &&

    {revokeAll.error.message}

    } +
    + ) +}