diff --git a/src/App.tsx b/src/App.tsx index e9c1078..d877c99 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 ( - + + + ) } diff --git a/src/api/bao.test.ts b/src/api/bao.test.ts new file mode 100644 index 0000000..53636ab --- /dev/null +++ b/src/api/bao.test.ts @@ -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)['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, '') + 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') + }) +}) diff --git a/src/api/bao.ts b/src/api/bao.ts new file mode 100644 index 0000000..7ad31cb --- /dev/null +++ b/src/api/bao.ts @@ -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=).' + +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(method: Method, path: string, body?: unknown): Promise { + const headers: Record = {} + 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 { + 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 { + return this.request('GET', 'sys/health?standbyok=true&sealedcode=200&uninitcode=200&perfstandbyok=true') + } + + async lookupSelf(): Promise { + const res = await this.request<{ data: TokenInfo }>('GET', 'auth/token/lookup-self') + return res.data + } + + async loginUserpass(username: string, password: string): Promise { + 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 } + } +} diff --git a/src/api/session.tsx b/src/api/session.tsx new file mode 100644 index 0000000..17ba52c --- /dev/null +++ b/src/api/session.tsx @@ -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( + () => ({ + client: state?.client ?? null, + tokenInfo: state?.tokenInfo ?? null, + connect: (client, tokenInfo) => setState({ client, tokenInfo }), + disconnect: () => setState(null), + }), + [state], + ) + return {children} +} diff --git a/src/api/useSession.ts b/src/api/useSession.ts new file mode 100644 index 0000000..91671c7 --- /dev/null +++ b/src/api/useSession.ts @@ -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(null) + +export function useSession(): Session { + const s = useContext(SessionContext) + if (!s) throw new Error('useSession must be used inside SessionProvider') + return s +} diff --git a/src/features/connect/ConnectPage.test.tsx b/src/features/connect/ConnectPage.test.tsx new file mode 100644 index 0000000..42c5423 --- /dev/null +++ b/src/features/connect/ConnectPage.test.tsx @@ -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( + + + , + ) + 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') +}) diff --git a/src/features/connect/ConnectPage.tsx b/src/features/connect/ConnectPage.tsx index 113d565..274b42c 100644 --- a/src/features/connect/ConnectPage.tsx +++ b/src/features/connect/ConnectPage.tsx @@ -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

Connect

+ const { client, tokenInfo, connect, disconnect } = useSession() + const [url, setUrl] = useState(client?.baseUrl ?? 'http://127.0.0.1:8200') + const [mode, setMode] = useState('token') + const [token, setToken] = useState('') + const [username, setUsername] = useState('') + const [password, setPassword] = useState('') + const [health, setHealth] = useState(null) + const [error, setError] = useState(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 ( +
+

Connect

+ {client && tokenInfo && ( +

+ Connected to {client.baseUrl} as {tokenInfo.display_name || 'token'} (policies: {tokenInfo.policies.join(', ')}){' '} + +

+ )} +
+ +
+ Login method + + +
+ {mode === 'token' ? ( + + ) : ( + <> + + + + )} + +
+ {health && ( +

+ Server: OpenBao {health.version}, {health.sealed ? 'sealed' : 'unsealed'} + {health.standby ? ', standby' : ''} +

+ )} + {error &&

{error}

} +
+ ) } diff --git a/src/index.css b/src/index.css index bb725ef..a2283f4 100644 --- a/src/index.css +++ b/src/index.css @@ -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; +} diff --git a/src/routes.test.tsx b/src/routes.test.tsx index 5889661..ef3fcab 100644 --- a/src/routes.test.tsx +++ b/src/routes.test.tsx @@ -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() + render( + + + , + ) expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument() }) test('redirects / to identities', () => { const router = createMemoryRouter(routes, { initialEntries: ['/'] }) - render() + render( + + + , + ) expect(screen.getByRole('heading', { name: 'Identities' })).toBeInTheDocument() })