Hardening: session expiry and sealed handling, request timeout, list states, a11y, tested admin policy, security headers, README
CI / integration (push) Successful in 12s
CI / check (push) Successful in 15s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-20 11:42:01 +01:00
1 parent 265c618884
commit a63f7c0faa
30 files changed
+623 -76

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
import { useQuery } from '@tanstack/react-query'
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { Layout } from '../Layout'
import { Providers } from '../test/providers'
import { testQueryClient } from '../test/queryClient'
import { BaoClient, BaoError, type TokenInfo } from './bao'
import { SessionGuard } from './SessionGuard'
import { SessionProvider } from './session'
import { useSession } from './useSession'
const info = (ttl: number): TokenInfo => ({ accessor: 'a', display_name: 'me', policies: [], ttl, renewable: false })
function Harness({ client, ttl, failWith }: { client: BaoClient; ttl: number; failWith?: BaoError }) {
const { connect, client: c } = useSession()
useQuery({
queryKey: ['probe'],
queryFn: () => (failWith ? Promise.reject(failWith) : Promise.resolve('ok')),
enabled: !!c,
})
return (
<>
<button type="button" onClick={() => connect(client, info(ttl))}>
go
</button>
</>
)
}
function setup(client: BaoClient, ttl = 0, failWith?: BaoError, qc = testQueryClient()) {
render(
<Providers client={qc}>
<SessionProvider>
<SessionGuard />
<MemoryRouter>
<Harness client={client} ttl={ttl} failWith={failWith} />
<Layout />
</MemoryRouter>
</SessionProvider>
</Providers>,
)
}
beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }))
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
test('the session ends when the token TTL elapses', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(new BaoClient('http://b', 't'), 60)
await user.click(screen.getByRole('button', { name: 'go' }))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
act(() => vi.advanceTimersByTime(61_000))
expect(await screen.findByRole('alert')).toHaveTextContent('expired')
expect(screen.getByRole('link', { name: 'Sign in again' })).toHaveAttribute('href', '/connect')
})
test('a token with no TTL never expires by timer', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(new BaoClient('http://b', 't'), 0)
await user.click(screen.getByRole('button', { name: 'go' }))
act(() => vi.advanceTimersByTime(10 * 365 * 86_400_000))
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
})
test('a 403 ends the session only if the token itself is dead', async () => {
const client = new BaoClient('http://b', 't')
const forbidden = new BaoError('forbidden', 'permission denied', 403)
const lookup = vi.spyOn(client, 'lookupSelf').mockResolvedValue(info(0))
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(client, 0, forbidden)
await user.click(screen.getByRole('button', { name: 'go' }))
await vi.waitFor(() => expect(lookup).toHaveBeenCalled())
expect(screen.queryByRole('alert')).not.toBeInTheDocument() // token fine: just missing permission
lookup.mockRejectedValue(forbidden)
await act(() => vi.waitFor(() => expect(screen.queryByRole('alert')).toBeNull()))
})
test('a revoked token (lookup-self also 403) ends the session', async () => {
const client = new BaoClient('http://b', 't')
const forbidden = new BaoError('forbidden', 'permission denied', 403)
vi.spyOn(client, 'lookupSelf').mockRejectedValue(forbidden)
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(client, 0, forbidden)
await user.click(screen.getByRole('button', { name: 'go' }))
expect(await screen.findByRole('alert')).toHaveTextContent('expired or the token was revoked')
})
test('a 503 from a sealed OpenBao ends the session with a sealed notice', async () => {
const client = new BaoClient('http://b', 't')
vi.spyOn(client, 'health').mockResolvedValue({ initialized: true, sealed: true, standby: false, version: '2' })
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(client, 0, new BaoError('unavailable', 'OpenBao is sealed or unavailable.', 503))
await user.click(screen.getByRole('button', { name: 'go' }))
expect(await screen.findByRole('alert')).toHaveTextContent('sealed')
})
test('a 503 from an unsealed OpenBao keeps the session', async () => {
const client = new BaoClient('http://b', 't')
const health = vi.spyOn(client, 'health').mockResolvedValue({ initialized: true, sealed: false, standby: true, version: '2' })
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(client, 0, new BaoError('unavailable', 'x', 503))
await user.click(screen.getByRole('button', { name: 'go' }))
await vi.waitFor(() => expect(health).toHaveBeenCalled())
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
})
test('ending the session clears cached OpenBao data', async () => {
const qc = testQueryClient()
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
setup(new BaoClient('http://b', 't'), 60, undefined, qc)
await user.click(screen.getByRole('button', { name: 'go' }))
await vi.waitFor(() => expect(qc.getQueryData(['probe'])).toBe('ok'))
act(() => vi.advanceTimersByTime(61_000))
await vi.waitFor(() => expect(qc.getQueryData(['probe'])).toBeUndefined())
})
+48
View File
@@ -0,0 +1,48 @@
import { useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
import { BaoError } from './bao'
import { useSession } from './useSession'
const isAuthFailure = (e: BaoError) => e.kind === 'forbidden' || e.kind === 'auth'
/**
* OpenBao answers 403 both for "token expired/revoked" and for "no permission", so a failed request
* alone proves nothing. On such errors, check the token itself (lookup-self is allowed by the default
* policy); on 503, check whether OpenBao has been sealed. Only then end the session.
*/
export function SessionGuard() {
const qc = useQueryClient()
const { client, expire } = useSession()
useEffect(() => {
if (!client) return
let checking = false
const onError = async (error: unknown) => {
if (!(error instanceof BaoError) || checking) return
checking = true
try {
if (isAuthFailure(error)) {
await client.lookupSelf()
} else if (error.kind === 'unavailable') {
if ((await client.health()).sealed) expire('sealed')
}
} catch (e) {
if (e instanceof BaoError && isAuthFailure(e)) expire('expired')
} finally {
checking = false
}
}
const unsubQ = qc.getQueryCache().subscribe((ev) => {
if (ev.type === 'updated' && ev.action.type === 'error') void onError(ev.query.state.error)
})
const unsubM = qc.getMutationCache().subscribe((ev) => {
if (ev.type === 'updated' && ev.action.type === 'error') void onError(ev.mutation.state.error)
})
return () => {
unsubQ()
unsubM()
}
}, [client, qc, expire])
return null
}
+100
View File
@@ -0,0 +1,100 @@
import { readFileSync } from 'node:fs'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { BaoClient } from './bao'
import { getGrantState, grantAccess, revokeAccess } from './grants'
import * as ids from './identities'
import * as secrets from './secrets'
import * as tokens from './tokens'
import { kvGrantRules } from '../model/managed'
// Everything the UI does, run with ONLY docs/envbao-admin.hcl (plus the default policy), so the
// documented least-privilege policy can't silently drift from what the app needs.
const root = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const policyName = `it-admin-${sfx}`
let admin: BaoClient
let adminToken: tokens.CreatedToken
beforeAll(async () => {
const auth = await root.request<{ data: Record<string, { type: string }> }>('GET', 'sys/auth')
if (!Object.values(auth.data).some((m) => m.type === 'userpass')) {
await root.request('POST', 'sys/auth/userpass', { type: 'userpass' })
}
await root.request('PUT', `sys/policies/acl/${policyName}`, { policy: readFileSync('docs/envbao-admin.hcl', 'utf8') })
adminToken = await tokens.createToken(root, { displayName: policyName, policies: [policyName], renewable: false, orphan: false })
admin = root.withToken(adminToken.token)
})
afterAll(async () => {
await tokens.revokeToken(root, adminToken.accessor).catch(() => {})
await root.request('DELETE', `sys/policies/acl/${policyName}`).catch(() => {})
})
describe('the documented admin policy is sufficient for every UI operation', () => {
const user = `it-pol-u-${sfx}`
const entity = `it-pol-e-${sfx}`
const group = `it-pol-g-${sfx}`
afterAll(async () => {
await ids.deleteGroup(root, group).catch(() => {})
await ids.deleteEntity(root, entity).catch(() => {})
await ids.deleteUser(root, user).catch(() => {})
await root.request('DELETE', `sys/policies/acl/envbao-user-${user}`).catch(() => {})
await root.request('DELETE', `sys/policies/acl/envbao-group-${group}`).catch(() => {})
})
test('connect and discovery', async () => {
expect((await admin.lookupSelf()).policies).toContain(policyName)
expect((await secrets.listKvMounts(admin)).map((m) => m.path)).toContain('secret/')
expect(await ids.userpassAccessor(admin)).toBeTruthy()
await secrets.listSecrets(admin, 'secret/', '')
await ids.listPolicyNames(admin)
})
test('users, entities, aliases and groups', async () => {
await ids.saveUser(admin, { name: user, password: 'pw-123456', policies: ['default'] })
expect((await ids.listUsers(admin)).some((u) => u.name === user)).toBe(true)
await ids.saveEntity(admin, { name: entity, policies: [] })
const e = await ids.readEntity(admin, entity)
await ids.addAlias(admin, { name: user, entityId: e.id, mountAccessor: (await ids.userpassAccessor(admin))! })
const withAlias = await ids.readEntity(admin, entity)
expect(withAlias.aliases).toHaveLength(1)
await ids.listEntities(admin)
await ids.saveGroup(admin, { name: group, policies: [], memberEntityIds: [e.id] })
await ids.listGroups(admin)
await ids.deleteAlias(admin, withAlias.aliases[0].id)
await ids.deleteGroup(admin, group)
await ids.deleteEntity(admin, entity)
})
test('tokens: create, list, inspect, revoke', async () => {
const t = await tokens.createToken(admin, { displayName: 'it-pol', policies: ['default'], ttl: '5m', renewable: false, orphan: false })
expect((await tokens.listTokens(admin)).some((x) => x.accessor === t.accessor)).toBe(true)
await tokens.revokeToken(admin, t.accessor)
})
test('grant and revoke', async () => {
const target = { kind: 'user' as const, name: user }
await grantAccess(admin, target, kvGrantRules('secret/', `it-pol-${sfx}/*`, ['read', 'list']))
expect((await getGrantState(admin, target)).attached).toBe(true)
await revokeAccess(admin, target, [`secret/data/it-pol-${sfx}/*`, `secret/metadata/it-pol-${sfx}/*`])
expect((await getGrantState(admin, target)).attached).toBe(false)
})
test('the access graph inputs can be read', async () => {
// (other test files create and delete policies concurrently, so only check ones we know exist)
expect(await ids.listPolicyNames(admin)).toEqual(expect.arrayContaining(['default', policyName]))
expect(await secrets.readPolicyHcl(admin, 'default')).not.toBeNull()
expect(await secrets.readPolicyHcl(admin, policyName)).toContain('sys/policies/acl')
})
test('orphan tokens need sudo, which the policy deliberately omits', async () => {
// surfaced to the user verbatim by the Tokens tab
await expect(
tokens.createToken(admin, { displayName: 'it-orphan', policies: ['default'], renewable: false, orphan: true }),
).rejects.toThrow(/sudo/)
})
})
+17
View File
@@ -47,11 +47,28 @@ describe('BaoClient', () => {
[403, 'forbidden'],
[404, 'not-found'],
[500, 'server'],
[503, 'unavailable'],
])('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('503 explains that OpenBao is sealed or unavailable', async () => {
mockFetch(503, { errors: ['Vault is sealed'] })
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toThrow('sealed or unavailable')
})
test('a timeout is reported as such, not as a CORS problem', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('slow', 'TimeoutError')))
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toThrow('did not respond within')
})
test('passes a timeout signal to fetch', async () => {
const fn = mockFetch(200, {})
await new BaoClient('http://b').request('GET', 'x')
expect((fn.mock.calls[0] as unknown as [string, RequestInit])[1].signal).toBeInstanceOf(AbortSignal)
})
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' })
+12 -3
View File
@@ -1,4 +1,4 @@
export type BaoErrorKind = 'network' | 'auth' | 'forbidden' | 'not-found' | 'server' | 'bad-response'
export type BaoErrorKind = 'network' | 'auth' | 'forbidden' | 'not-found' | 'unavailable' | 'server' | 'bad-response'
export class BaoError extends Error {
readonly kind: BaoErrorKind
@@ -49,7 +49,10 @@ export function normaliseBaseUrl(url: string): string {
return trimmed
}
export const REQUEST_TIMEOUT_MS = 15_000
function kindForStatus(status: number): BaoErrorKind {
if (status === 503) return 'unavailable'
if (status === 401) return 'auth'
if (status === 403) return 'forbidden'
if (status === 404) return 'not-found'
@@ -80,8 +83,12 @@ export class BaoClient {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
} catch {
} catch (e) {
if (e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError')) {
throw new BaoError('network', `OpenBao did not respond within ${REQUEST_TIMEOUT_MS / 1000} seconds.`)
}
throw new BaoError('network', CORS_HINT)
}
@@ -100,7 +107,9 @@ export class BaoClient {
const message =
res.status === 401 || res.status === 403
? errors.join('; ') || 'Permission denied'
: errors.join('; ') || `OpenBao returned HTTP ${res.status}`
: res.status === 503
? 'OpenBao is sealed or unavailable.'
: errors.join('; ') || `OpenBao returned HTTP ${res.status}`
throw new BaoError(kindForStatus(res.status), message, res.status, errors)
}
return json as T
+37 -5
View File
@@ -1,18 +1,50 @@
import { useMemo, useState, type ReactNode } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import type { BaoClient, TokenInfo } from './bao'
import { SessionContext, type Session } from './useSession'
import { SessionContext, type Session, type SessionNotice } from './useSession'
// setTimeout overflows (fires immediately) above this
const MAX_TIMEOUT_MS = 2 ** 31 - 1
// The token lives only in React state (memory); a page reload logs out.
export function SessionProvider({ children }: { children: ReactNode }) {
const qc = useQueryClient()
const [state, setState] = useState<{ client: BaoClient; tokenInfo: TokenInfo } | null>(null)
const [notice, setNotice] = useState<SessionNotice | null>(null)
const [lastUrl, setLastUrl] = useState<string | null>(null)
// Drop cached OpenBao data whenever the session ends so it can't leak into the next one.
const end = useCallback(
(n: SessionNotice | null) => {
setState(null)
setNotice(n)
qc.clear()
},
[qc],
)
const ttl = state?.tokenInfo.ttl ?? 0
useEffect(() => {
if (!state || ttl <= 0) return // ttl 0 means the token never expires
const t = setTimeout(() => end('expired'), Math.min(ttl * 1000, MAX_TIMEOUT_MS))
return () => clearTimeout(t)
}, [state, ttl, end])
const value = useMemo<Session>(
() => ({
client: state?.client ?? null,
tokenInfo: state?.tokenInfo ?? null,
connect: (client, tokenInfo) => setState({ client, tokenInfo }),
disconnect: () => setState(null),
notice,
lastUrl,
connect: (client, tokenInfo) => {
setState({ client, tokenInfo })
setLastUrl(client.baseUrl)
setNotice(null)
},
disconnect: () => end(null),
expire: end,
}),
[state],
[state, notice, lastUrl, end],
)
return <SessionContext value={value}>{children}</SessionContext>
}
+7
View File
@@ -1,11 +1,18 @@
import { createContext, useContext } from 'react'
import type { BaoClient, TokenInfo } from './bao'
/** Why the session ended without the user disconnecting. */
export type SessionNotice = 'expired' | 'sealed'
export interface Session {
client: BaoClient | null
tokenInfo: TokenInfo | null
notice: SessionNotice | null
/** URL of the last connection, so signing in again doesn't mean retyping it. */
lastUrl: string | null
connect: (client: BaoClient, tokenInfo: TokenInfo) => void
disconnect: () => void
expire: (notice: SessionNotice) => void
}
export const SessionContext = createContext<Session | null>(null)