Add token management: create, list, revoke with show-once secret
CI / integration (push) Successful in 10s
CI / check (push) Successful in 13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-20 11:21:24 +01:00
1 parent 0e1e8988bd
commit f2ba697093
6 files changed
+373 -1

No files matched your search

+3 -1
View File
@@ -2,9 +2,10 @@ import { useState } from 'react'
import { RequireConnection } from '../shared/RequireConnection'
import { EntitiesTab } from './EntitiesTab'
import { GroupsTab } from './GroupsTab'
import { TokensTab } from './TokensTab'
import { UsersTab } from './UsersTab'
const tabs = ['Users', 'Entities', 'Groups'] as const
const tabs = ['Users', 'Entities', 'Groups', 'Tokens'] as const
type Tab = (typeof tabs)[number]
export function IdentitiesPage() {
@@ -25,6 +26,7 @@ export function IdentitiesPage() {
{tab === 'Users' && <UsersTab client={client} />}
{tab === 'Entities' && <EntitiesTab client={client} />}
{tab === 'Groups' && <GroupsTab client={client} />}
{tab === 'Tokens' && <TokensTab client={client} />}
</>
)}
</RequireConnection>
@@ -0,0 +1,88 @@
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 ids from '../../api/identities'
import { SessionProvider } from '../../api/session'
import * as api from '../../api/tokens'
import { TokensTab } from './TokensTab'
vi.mock('../../api/identities')
vi.mock('../../api/tokens')
const client = new BaoClient('http://b', 't')
const token = (over: Partial<api.TokenSummary>): api.TokenSummary => ({
accessor: 'acc-aaaaaaaa',
display_name: 'token-ci',
policies: ['dev'],
ttl: 7200,
renewable: true,
orphan: false,
creation_time: '',
expire_time: null,
...over,
})
beforeEach(() => {
vi.mocked(api.listTokens).mockResolvedValue([token({})])
vi.mocked(ids.listPolicyNames).mockResolvedValue(['default', 'dev'])
})
afterEach(() => vi.resetAllMocks())
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<SessionProvider>
<TokensTab client={client} />
</SessionProvider>
</QueryClientProvider>,
)
return userEvent.setup()
}
test('lists tokens with a human TTL', async () => {
setup()
const row = (await screen.findByText('token-ci')).closest('tr')!
expect(within(row).getByText('2h')).toBeInTheDocument()
})
test('creates a token and shows its value once', async () => {
vi.mocked(api.createToken).mockResolvedValue({ token: 'hvs.SECRET', accessor: 'x', policies: ['dev'] })
const user = setup()
await user.click(await screen.findByRole('button', { name: 'New token' }))
await user.type(screen.getByLabelText('Display name'), 'ci')
await user.type(screen.getByLabelText('TTL'), '24h')
await user.click(await screen.findByLabelText('dev'))
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(api.createToken).toHaveBeenCalledWith(client, {
displayName: 'ci',
policies: ['dev'],
ttl: '24h',
renewable: true,
orphan: false,
})
expect(await screen.findByText('hvs.SECRET')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Done' }))
expect(screen.queryByText('hvs.SECRET')).not.toBeInTheDocument()
})
test('revoke requires confirmation', async () => {
vi.mocked(api.revokeToken).mockResolvedValue()
const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Revoke' }))
expect(api.revokeToken).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Revoke' }))
expect(api.revokeToken).toHaveBeenCalledWith(client, 'acc-aaaaaaaa')
confirm.mockRestore()
})
test('shows create errors', async () => {
vi.mocked(api.createToken).mockRejectedValue(new Error('permission denied'))
const user = setup()
await user.click(await screen.findByRole('button', { name: 'New token' }))
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+159
View File
@@ -0,0 +1,159 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { createToken, listTokens, revokeToken, type CreatedToken } from '../../api/tokens'
import { useSession } from '../../api/useSession'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
displayName: string
policies: string[]
ttl: string
renewable: boolean
orphan: boolean
}
const empty: Draft = { displayName: '', policies: [], ttl: '', renewable: true, orphan: false }
function formatTtl(seconds: number): string {
if (!seconds) return 'no expiry'
if (seconds < 3600) return `${Math.round(seconds / 60)}m`
if (seconds < 86400) return `${Math.round(seconds / 3600)}h`
return `${Math.round(seconds / 86400)}d`
}
export function TokensTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const { tokenInfo } = useSession()
const tokens = useQuery({ queryKey: ['tokens'], queryFn: () => listTokens(client) })
const [draft, setDraft] = useState<Draft | null>(null)
// The token value is only ever held here, and cleared when dismissed.
const [created, setCreated] = useState<CreatedToken | null>(null)
const [copied, setCopied] = useState(false)
const create = useMutation({
mutationFn: (d: Draft) => createToken(client, d),
onSuccess: (t) => {
setDraft(null)
setCreated(t)
setCopied(false)
return qc.invalidateQueries({ queryKey: ['tokens'] })
},
})
const revoke = useMutation({
mutationFn: (accessor: string) => revokeToken(client, accessor),
onSuccess: () => qc.invalidateQueries({ queryKey: ['tokens'] }),
})
function submit(e: FormEvent) {
e.preventDefault()
if (draft) create.mutate(draft)
}
async function copy() {
if (!created) return
try {
await navigator.clipboard.writeText(created.token)
setCopied(true)
} catch {
setCopied(false)
}
}
return (
<section>
{created && (
<div role="status" className="secret-once">
<p>
<strong>Copy this token now. It will not be shown again.</strong>
</p>
<code>{created.token}</code>{' '}
<button type="button" onClick={copy}>
{copied ? 'Copied' : 'Copy'}
</button>{' '}
<button type="button" onClick={() => setCreated(null)}>
Done
</button>
</div>
)}
{tokens.error && <p role="alert">{tokens.error.message}</p>}
<table>
<thead>
<tr>
<th>Name</th>
<th>Policies</th>
<th>Expires</th>
<th>Accessor</th>
<th />
</tr>
</thead>
<tbody>
{tokens.data?.map((t) => {
const isSelf = t.accessor === tokenInfo?.accessor
return (
<tr key={t.accessor}>
<td>
{t.display_name || '—'}
{isSelf ? ' (you)' : ''}
</td>
<td>{t.policies.join(', ') || '—'}</td>
<td>{formatTtl(t.ttl)}</td>
<td>
<code>{t.accessor.slice(0, 8)}…</code>
</td>
<td>
<button
type="button"
disabled={isSelf}
title={isSelf ? 'This is the token you are signed in with' : undefined}
onClick={() =>
window.confirm(`Revoke token "${t.display_name || t.accessor}"? Tokens created from it are revoked too.`) &&
revoke.mutate(t.accessor)
}
>
Revoke
</button>
</td>
</tr>
)
})}
</tbody>
</table>
{revoke.error && <p role="alert">{revoke.error.message}</p>}
{!draft && (
<button type="button" onClick={() => setDraft(empty)}>
New token
</button>
)}
{draft && (
<form onSubmit={submit} aria-label="New token">
<label>
Display name
<input value={draft.displayName} onChange={(e) => setDraft({ ...draft, displayName: e.target.value })} />
</label>
<label>
TTL
<input value={draft.ttl} onChange={(e) => setDraft({ ...draft, ttl: e.target.value })} placeholder="e.g. 24h (blank = default)" />
</label>
<label className="check">
<input type="checkbox" checked={draft.renewable} onChange={(e) => setDraft({ ...draft, renewable: e.target.checked })} /> Renewable
</label>
<label className="check">
<input type="checkbox" checked={draft.orphan} onChange={(e) => setDraft({ ...draft, orphan: e.target.checked })} /> Orphan
(outlives the token you are signed in with; requires sudo)
</label>
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
{create.error && <p role="alert">{create.error.message}</p>}
<div>
<button type="submit" disabled={create.isPending}>
Create
</button>{' '}
<button type="button" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
</section>
)
}