diff --git a/src/api/tokens.integration.test.ts b/src/api/tokens.integration.test.ts new file mode 100644 index 0000000..c57fa1e --- /dev/null +++ b/src/api/tokens.integration.test.ts @@ -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) + }) +}) diff --git a/src/api/tokens.ts b/src/api/tokens.ts new file mode 100644 index 0000000..6a6e514 --- /dev/null +++ b/src/api/tokens.ts @@ -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 { + 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 { + 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 { + 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 { + await c.request('POST', 'auth/token/revoke-accessor', { accessor }) +} diff --git a/src/features/identities/IdentitiesPage.tsx b/src/features/identities/IdentitiesPage.tsx index 4b8dc40..dce96a7 100644 --- a/src/features/identities/IdentitiesPage.tsx +++ b/src/features/identities/IdentitiesPage.tsx @@ -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' && } {tab === 'Entities' && } {tab === 'Groups' && } + {tab === 'Tokens' && } )} diff --git a/src/features/identities/TokensTab.test.tsx b/src/features/identities/TokensTab.test.tsx new file mode 100644 index 0000000..3c05749 --- /dev/null +++ b/src/features/identities/TokensTab.test.tsx @@ -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 => ({ + 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( + + + + + , + ) + 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') +}) diff --git a/src/features/identities/TokensTab.tsx b/src/features/identities/TokensTab.tsx new file mode 100644 index 0000000..354725c --- /dev/null +++ b/src/features/identities/TokensTab.tsx @@ -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(null) + // The token value is only ever held here, and cleared when dismissed. + const [created, setCreated] = useState(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 ( +
+ {created && ( +
+

+ Copy this token now. It will not be shown again. +

+ {created.token}{' '} + {' '} + +
+ )} + {tokens.error &&

{tokens.error.message}

} + + + + + + + + + + + {tokens.data?.map((t) => { + const isSelf = t.accessor === tokenInfo?.accessor + return ( + + + + + + + + ) + })} + +
NamePoliciesExpiresAccessor +
+ {t.display_name || '—'} + {isSelf ? ' (you)' : ''} + {t.policies.join(', ') || '—'}{formatTtl(t.ttl)} + {t.accessor.slice(0, 8)}… + + +
+ {revoke.error &&

{revoke.error.message}

} + {!draft && ( + + )} + {draft && ( +
+ + + + + setDraft({ ...draft, policies })} /> + {create.error &&

{create.error.message}

} +
+ {' '} + +
+ + )} +
+ ) +} diff --git a/src/index.css b/src/index.css index 2bf999a..3393374 100644 --- a/src/index.css +++ b/src/index.css @@ -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; +}