Add OpenBao API client, session context and connect screen
CI / integration (push) Successful in 9s
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:05:59 +01:00
1 parent c5dbb78d1b
commit de36c97f36
9 files changed
+438 -4

No files matched your search

+4 -1
View File
@@ -1,5 +1,6 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createBrowserRouter, RouterProvider } from 'react-router'
import { SessionProvider } from './api/session'
import { routes } from './routes'
const queryClient = new QueryClient()
@@ -8,7 +9,9 @@ const router = createBrowserRouter(routes)
function App() {
return (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</QueryClientProvider>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { BaoClient, BaoError, normaliseBaseUrl } from './bao'
function mockFetch(status: number, body?: unknown) {
const fn = vi.fn(async () =>
status === 204
? new Response(null, { status })
: new Response(typeof body === 'string' ? body : JSON.stringify(body), { status }),
)
vi.stubGlobal('fetch', fn)
return fn
}
afterEach(() => vi.unstubAllGlobals())
describe('normaliseBaseUrl', () => {
test('strips trailing slashes', () => expect(normaliseBaseUrl(' http://x:8200// ')).toBe('http://x:8200'))
test('rejects missing scheme', () => expect(() => normaliseBaseUrl('x:8200')).toThrow(BaoError))
})
describe('BaoClient', () => {
test('sends token header and builds url', async () => {
const fn = mockFetch(200, { data: { x: 1 } })
await new BaoClient('http://b:8200/', 't0k').request('GET', '/sys/policies/acl')
const [url, init] = fn.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('http://b:8200/v1/sys/policies/acl')
expect((init.headers as Record<string, string>)['X-Vault-Token']).toBe('t0k')
})
test('sends JSON body', async () => {
const fn = mockFetch(204)
await new BaoClient('http://b').request('POST', 'x', { a: 1 })
const init = (fn.mock.calls[0] as unknown as [string, RequestInit])[1]
expect(init.body).toBe('{"a":1}')
})
test('maps network failure to CORS guidance', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toMatchObject({
kind: 'network',
message: expect.stringContaining('CORS'),
})
})
test.each([
[401, 'auth'],
[403, 'forbidden'],
[404, 'not-found'],
[500, 'server'],
])('maps HTTP %i to %s', async (status, kind) => {
mockFetch(status, { errors: ['nope'] })
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toMatchObject({ kind, status })
})
test('non-JSON success is a bad-response', async () => {
mockFetch(200, '<html>')
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toMatchObject({ kind: 'bad-response' })
})
test('list returns keys and treats 404 as empty', async () => {
mockFetch(200, { data: { keys: ['a', 'b/'] } })
expect(await new BaoClient('http://b').list('secret/metadata')).toEqual(['a', 'b/'])
const fn = mockFetch(404, { errors: [] })
expect(await new BaoClient('http://b').list('secret/metadata/')).toEqual([])
expect((fn.mock.calls[0] as unknown as [string])[0]).toBe('http://b/v1/secret/metadata/?list=true')
})
test('loginUserpass returns token', async () => {
const fn = mockFetch(200, { auth: { client_token: 'hvs.x', policies: ['default'], lease_duration: 60 } })
const r = await new BaoClient('http://b').loginUserpass('al ice', 'pw')
expect(r).toEqual({ token: 'hvs.x', policies: ['default'], leaseDuration: 60 })
expect((fn.mock.calls[0] as unknown as [string])[0]).toBe('http://b/v1/auth/userpass/login/al%20ice')
})
})
+137
View File
@@ -0,0 +1,137 @@
export type BaoErrorKind = 'network' | 'auth' | 'forbidden' | 'not-found' | 'server' | 'bad-response'
export class BaoError extends Error {
readonly kind: BaoErrorKind
readonly status?: number
readonly errors: string[]
constructor(kind: BaoErrorKind, message: string, status?: number, errors: string[] = []) {
super(message)
this.name = 'BaoError'
this.kind = kind
this.status = status
this.errors = errors
}
}
export interface BaoHealth {
initialized: boolean
sealed: boolean
standby: boolean
version: string
cluster_name?: string
}
export interface TokenInfo {
id?: string
accessor: string
display_name: string
policies: string[]
ttl: number
renewable: boolean
}
export interface LoginResult {
token: string
policies: string[]
leaseDuration: number
}
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'
const CORS_HINT =
'Could not reach OpenBao. Check the URL, that the server is running, and that CORS allows this origin ' +
'(bao write sys/config/cors enabled=true allowed_origins=<this origin>).'
export function normaliseBaseUrl(url: string): string {
const trimmed = url.trim().replace(/\/+$/, '')
if (!/^https?:\/\//i.test(trimmed)) throw new BaoError('network', 'URL must start with http:// or https://')
return trimmed
}
function kindForStatus(status: number): BaoErrorKind {
if (status === 401) return 'auth'
if (status === 403) return 'forbidden'
if (status === 404) return 'not-found'
return 'server'
}
export class BaoClient {
readonly baseUrl: string
private token: string | undefined
constructor(baseUrl: string, token?: string) {
this.baseUrl = normaliseBaseUrl(baseUrl)
this.token = token
}
withToken(token: string): BaoClient {
return new BaoClient(this.baseUrl, token)
}
async request<T = unknown>(method: Method, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = {}
if (this.token) headers['X-Vault-Token'] = this.token
if (body !== undefined) headers['Content-Type'] = 'application/json'
let res: Response
try {
res = await fetch(`${this.baseUrl}/v1/${path.replace(/^\/+/, '')}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
})
} catch {
throw new BaoError('network', CORS_HINT)
}
if (res.status === 204) return undefined as T
let json: unknown
try {
json = await res.json()
} catch {
if (res.ok) throw new BaoError('bad-response', 'OpenBao returned a non-JSON response. Is the URL correct?', res.status)
throw new BaoError(kindForStatus(res.status), `OpenBao returned HTTP ${res.status}`, res.status)
}
if (!res.ok) {
const errors = (json as { errors?: string[] }).errors ?? []
const message =
res.status === 401 || res.status === 403
? errors.join('; ') || 'Permission denied'
: errors.join('; ') || `OpenBao returned HTTP ${res.status}`
throw new BaoError(kindForStatus(res.status), message, res.status, errors)
}
return json as T
}
async list(path: string): Promise<string[]> {
try {
const res = await this.request<{ data: { keys: string[] } }>('GET', `${path.replace(/\/+$/, '')}/?list=true`)
return res.data.keys
} catch (e) {
if (e instanceof BaoError && e.kind === 'not-found') return []
throw e
}
}
/** Unauthenticated; sealed/standby/uninitialised states still return a body. */
async health(): Promise<BaoHealth> {
return this.request<BaoHealth>('GET', 'sys/health?standbyok=true&sealedcode=200&uninitcode=200&perfstandbyok=true')
}
async lookupSelf(): Promise<TokenInfo> {
const res = await this.request<{ data: TokenInfo }>('GET', 'auth/token/lookup-self')
return res.data
}
async loginUserpass(username: string, password: string): Promise<LoginResult> {
const res = await this.request<{ auth: { client_token: string; policies: string[]; lease_duration: number } }>(
'POST',
`auth/userpass/login/${encodeURIComponent(username)}`,
{ password },
)
return { token: res.auth.client_token, policies: res.auth.policies, leaseDuration: res.auth.lease_duration }
}
}
+18
View File
@@ -0,0 +1,18 @@
import { useMemo, useState, type ReactNode } from 'react'
import type { BaoClient, TokenInfo } from './bao'
import { SessionContext, type Session } from './useSession'
// The token lives only in React state (memory); a page reload logs out.
export function SessionProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<{ client: BaoClient; tokenInfo: TokenInfo } | null>(null)
const value = useMemo<Session>(
() => ({
client: state?.client ?? null,
tokenInfo: state?.tokenInfo ?? null,
connect: (client, tokenInfo) => setState({ client, tokenInfo }),
disconnect: () => setState(null),
}),
[state],
)
return <SessionContext value={value}>{children}</SessionContext>
}
+17
View File
@@ -0,0 +1,17 @@
import { createContext, useContext } from 'react'
import type { BaoClient, TokenInfo } from './bao'
export interface Session {
client: BaoClient | null
tokenInfo: TokenInfo | null
connect: (client: BaoClient, tokenInfo: TokenInfo) => void
disconnect: () => void
}
export const SessionContext = createContext<Session | null>(null)
export function useSession(): Session {
const s = useContext(SessionContext)
if (!s) throw new Error('useSession must be used inside SessionProvider')
return s
}
+63
View File
@@ -0,0 +1,63 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, test, vi } from 'vitest'
import { SessionProvider } from '../../api/session'
import { ConnectPage } from './ConnectPage'
const health = { initialized: true, sealed: false, standby: false, version: '2.1.0' }
const tokenInfo = { accessor: 'a', display_name: 'root', policies: ['root'], ttl: 0, renewable: false }
afterEach(() => vi.unstubAllGlobals())
function setup() {
render(
<SessionProvider>
<ConnectPage />
</SessionProvider>,
)
return userEvent.setup()
}
test('connects with a token', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (url: string) =>
new Response(JSON.stringify(url.includes('sys/health') ? health : { data: tokenInfo }), { status: 200 }),
),
)
const user = setup()
await user.type(screen.getByLabelText('Token', { selector: 'input[type=password]' }), 'root')
await user.click(screen.getByRole('button', { name: 'Connect' }))
expect(await screen.findByRole('status')).toHaveTextContent('Connected to http://127.0.0.1:8200 as root')
})
test('shows CORS guidance when unreachable', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
const user = setup()
await user.type(screen.getByLabelText('Token', { selector: 'input[type=password]' }), 'x')
await user.click(screen.getByRole('button', { name: 'Connect' }))
expect(await screen.findByRole('alert')).toHaveTextContent('CORS')
})
test('shows invalid token error', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (url: string) =>
url.includes('sys/health')
? new Response(JSON.stringify(health), { status: 200 })
: new Response(JSON.stringify({ errors: ['permission denied'] }), { status: 403 }),
),
)
const user = setup()
await user.type(screen.getByLabelText('Token', { selector: 'input[type=password]' }), 'bad')
await user.click(screen.getByRole('button', { name: 'Connect' }))
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
test('refuses a sealed server', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ...health, sealed: true }), { status: 200 })))
const user = setup()
await user.type(screen.getByLabelText('Token', { selector: 'input[type=password]' }), 'x')
await user.click(screen.getByRole('button', { name: 'Connect' }))
expect(await screen.findByRole('alert')).toHaveTextContent('sealed')
})
+99 -1
View File
@@ -1,3 +1,101 @@
import { useState, type FormEvent } from 'react'
import { BaoClient, BaoError, type BaoHealth } from '../../api/bao'
import { useSession } from '../../api/useSession'
type Mode = 'token' | 'userpass'
export function ConnectPage() {
return <h1>Connect</h1>
const { client, tokenInfo, connect, disconnect } = useSession()
const [url, setUrl] = useState(client?.baseUrl ?? 'http://127.0.0.1:8200')
const [mode, setMode] = useState<Mode>('token')
const [token, setToken] = useState('')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [health, setHealth] = useState<BaoHealth | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
setBusy(true)
setError(null)
setHealth(null)
try {
const anon = new BaoClient(url)
const h = await anon.health()
setHealth(h)
if (!h.initialized) throw new BaoError('server', 'OpenBao is not initialised.')
if (h.sealed) throw new BaoError('server', 'OpenBao is sealed. Unseal it before connecting.')
const authed = mode === 'token' ? anon.withToken(token) : anon.withToken((await anon.loginUserpass(username, password)).token)
connect(authed, await authed.lookupSelf())
setToken('')
setPassword('')
} catch (err) {
setError(
err instanceof BaoError && err.kind === 'auth' && mode === 'token'
? 'Invalid token.'
: err instanceof Error
? err.message
: String(err),
)
} finally {
setBusy(false)
}
}
return (
<section>
<h1>Connect</h1>
{client && tokenInfo && (
<p role="status">
Connected to {client.baseUrl} as {tokenInfo.display_name || 'token'} (policies: {tokenInfo.policies.join(', ')}){' '}
<button type="button" onClick={disconnect}>
Disconnect
</button>
</p>
)}
<form onSubmit={submit}>
<label>
OpenBao URL
<input value={url} onChange={(e) => setUrl(e.target.value)} required />
</label>
<fieldset>
<legend>Login method</legend>
<label>
<input type="radio" checked={mode === 'token'} onChange={() => setMode('token')} /> Token
</label>
<label>
<input type="radio" checked={mode === 'userpass'} onChange={() => setMode('userpass')} /> Userpass
</label>
</fieldset>
{mode === 'token' ? (
<label>
Token
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} required autoComplete="off" />
</label>
) : (
<>
<label>
Username
<input value={username} onChange={(e) => setUsername(e.target.value)} required />
</label>
<label>
Password
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
</label>
</>
)}
<button type="submit" disabled={busy}>
{busy ? 'Connecting…' : 'Connect'}
</button>
</form>
{health && (
<p>
Server: OpenBao {health.version}, {health.sealed ? 'sealed' : 'unsealed'}
{health.standby ? ', standby' : ''}
</p>
)}
{error && <p role="alert">{error}</p>}
</section>
)
}
+15
View File
@@ -33,3 +33,18 @@ body {
.shell main {
padding: 1rem;
}
form {
display: grid;
gap: 0.75rem;
max-width: 24rem;
}
form label {
display: grid;
gap: 0.25rem;
}
[role='alert'] {
color: #c0392b;
}
+11 -2
View File
@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { expect, test } from 'vitest'
import { SessionProvider } from './api/session'
import { routes } from './routes'
test.each([
@@ -10,12 +11,20 @@ test.each([
['/connect', 'Connect'],
])('renders %s', (path, heading) => {
const router = createMemoryRouter(routes, { initialEntries: [path] })
render(<RouterProvider router={router} />)
render(
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>,
)
expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument()
})
test('redirects / to identities', () => {
const router = createMemoryRouter(routes, { initialEntries: ['/'] })
render(<RouterProvider router={router} />)
render(
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>,
)
expect(screen.getByRole('heading', { name: 'Identities' })).toBeInTheDocument()
})