Add token management: create, list, revoke with show-once secret
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0e1e8988bd
commit
f2ba697093
6 files changed
+373
-1
No files matched your search
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { BaoClient } from './bao'
|
||||
import * as api from './tokens'
|
||||
|
||||
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
|
||||
|
||||
describe('token API against a dev OpenBao', () => {
|
||||
test('create, authenticate, list, revoke', async () => {
|
||||
const created = await api.createToken(client, {
|
||||
displayName: 'it-token',
|
||||
policies: ['default', 'it-extra'],
|
||||
ttl: '1h',
|
||||
renewable: false,
|
||||
orphan: false,
|
||||
})
|
||||
expect(created.token).toBeTruthy()
|
||||
|
||||
// the new token authenticates with the chosen policies
|
||||
const self = await client.withToken(created.token).lookupSelf()
|
||||
expect(self.policies.sort()).toEqual(['default', 'it-extra'])
|
||||
expect(self.display_name).toBe('token-it-token')
|
||||
expect(self.renewable).toBe(false)
|
||||
|
||||
const listed = await api.listTokens(client)
|
||||
expect(listed.find((t) => t.accessor === created.accessor)).toMatchObject({ display_name: 'token-it-token' })
|
||||
|
||||
await api.revokeToken(client, created.accessor)
|
||||
await expect(client.withToken(created.token).lookupSelf()).rejects.toMatchObject({ kind: 'forbidden' })
|
||||
expect((await api.listTokens(client)).some((t) => t.accessor === created.accessor)).toBe(false)
|
||||
})
|
||||
|
||||
test('orphan tokens survive revocation of their parent', async () => {
|
||||
const parent = await api.createToken(client, {
|
||||
displayName: 'it-parent',
|
||||
policies: ['root'],
|
||||
renewable: true,
|
||||
orphan: false,
|
||||
})
|
||||
const parentClient = client.withToken(parent.token)
|
||||
const child = await api.createToken(parentClient, {
|
||||
displayName: 'it-orphan',
|
||||
policies: ['default'],
|
||||
renewable: false,
|
||||
orphan: true,
|
||||
})
|
||||
const plain = await api.createToken(parentClient, {
|
||||
displayName: 'it-child',
|
||||
policies: ['default'],
|
||||
renewable: false,
|
||||
orphan: false,
|
||||
})
|
||||
await api.revokeToken(client, parent.accessor)
|
||||
expect((await client.withToken(child.token).lookupSelf()).policies).toContain('default')
|
||||
await expect(client.withToken(plain.token).lookupSelf()).rejects.toMatchObject({ kind: 'forbidden' })
|
||||
await api.revokeToken(client, child.accessor)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { BaoClient } from './bao'
|
||||
|
||||
export interface TokenSummary {
|
||||
accessor: string
|
||||
display_name: string
|
||||
policies: string[]
|
||||
/** Remaining TTL in seconds; 0 means no expiry (e.g. root). */
|
||||
ttl: number
|
||||
renewable: boolean
|
||||
orphan: boolean
|
||||
creation_time: string
|
||||
expire_time: string | null
|
||||
}
|
||||
|
||||
export interface CreateTokenInput {
|
||||
displayName: string
|
||||
policies: string[]
|
||||
ttl?: string
|
||||
renewable: boolean
|
||||
/** Detach from the creating token so it outlives it. Needs sudo. */
|
||||
orphan: boolean
|
||||
}
|
||||
|
||||
export interface CreatedToken {
|
||||
token: string
|
||||
accessor: string
|
||||
policies: string[]
|
||||
}
|
||||
|
||||
export async function lookupAccessor(c: BaoClient, accessor: string): Promise<TokenSummary> {
|
||||
const res = await c.request<{ data: TokenSummary }>('POST', 'auth/token/lookup-accessor', { accessor })
|
||||
return res.data
|
||||
}
|
||||
|
||||
/** A token can expire between listing and lookup, so individual failures are skipped. */
|
||||
export async function listTokens(c: BaoClient): Promise<TokenSummary[]> {
|
||||
const accessors = await c.list('auth/token/accessors')
|
||||
const found = await Promise.all(accessors.map((a) => lookupAccessor(c, a).catch(() => null)))
|
||||
return found.filter((t): t is TokenSummary => t !== null)
|
||||
}
|
||||
|
||||
export async function createToken(c: BaoClient, input: CreateTokenInput): Promise<CreatedToken> {
|
||||
const res = await c.request<{ auth: { client_token: string; accessor: string; policies: string[] } }>(
|
||||
'POST',
|
||||
'auth/token/create',
|
||||
{
|
||||
display_name: input.displayName || undefined,
|
||||
policies: input.policies,
|
||||
ttl: input.ttl || undefined,
|
||||
renewable: input.renewable,
|
||||
no_parent: input.orphan || undefined,
|
||||
},
|
||||
)
|
||||
return { token: res.auth.client_token, accessor: res.auth.accessor, policies: res.auth.policies }
|
||||
}
|
||||
|
||||
export async function revokeToken(c: BaoClient, accessor: string): Promise<void> {
|
||||
await c.request('POST', 'auth/token/revoke-accessor', { accessor })
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -75,3 +75,10 @@ td {
|
||||
label.check {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.secret-once {
|
||||
border: 2px solid #d4a017;
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
Reference in new issue
Block a user