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

+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
}