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

+89 -27
View File
@@ -6,6 +6,23 @@ Licensed under the [BSD 3-Clause License](LICENSE).
The UI talks directly to the OpenBao HTTP API from the browser. There is no backend. The UI talks directly to the OpenBao HTTP API from the browser. There is no backend.
## What it does
- **Connect** with a token or a userpass login. Refuses sealed or uninitialised servers, and explains CORS and connection problems.
- **Identities**: create, edit and delete userpass users, identity entities (with userpass aliases) and groups; create, list and revoke tokens. A new token's value is shown once.
- **Secrets**: browse KV v2 mounts and paths (names only; secret values are never read) and see which identities can reach a secret, through which policy, with which capabilities.
- **Access**: from an identity's **Access** button, grant it capabilities on a secret path (globs allowed) or revoke them, without writing policy HCL.
- **Graph**: Identity → Policy → Path graph, filterable by identity and path. Click a policy→path edge to revoke that grant.
## Using it
1. **Connect**: enter the OpenBao URL and a token (or userpass credentials).
2. **Identities → Users** (or Entities / Groups): create someone.
3. Click **Access** on that row, pick a secrets engine, enter a secret path such as `app/*`, tick the capabilities and **Grant**. The path is a KV path *within the mount*; EnvBao writes the `data/` and `metadata/` policy paths for you.
4. Check the result under **Secrets** (select the secret) or **Graph**.
Your session lasts as long as the token. When it expires, is revoked, or OpenBao is sealed, you'll see a banner with a link to sign in again. Reloading the page signs you out: the token is only held in memory.
## Quick start with Docker ## Quick start with Docker
```sh ```sh
@@ -67,28 +84,52 @@ bao secrets enable -path=secret -version=2 kv # skip if already mounted
### Admin policy for the UI ### Admin policy for the UI
Least privilege for the account that uses the UI: Least privilege for the account that uses the UI. The same policy is kept in [`docs/envbao-admin.hcl`](docs/envbao-admin.hcl), and the integration tests run every UI operation with only this policy, so it is known to be sufficient:
```hcl ```hcl
path "sys/policies/acl/*" { capabilities = ["create", "read", "update", "delete", "list"] } # Least-privilege policy for the account that uses EnvBao Admin.
path "sys/policies/acl" { capabilities = ["list"] } # Adjust "secret" if your KV v2 mount has a different path.
path "auth/userpass/users/*" { capabilities = ["create", "read", "update", "delete", "list"] }
path "auth/userpass/users" { capabilities = ["list"] } # Policies: list, read, create/update and delete (managed `envbao-*` and read-only viewing of the rest)
path "auth/token/create" { capabilities = ["create", "update"] } path "sys/policies/acl" { capabilities = ["list"] }
path "auth/token/lookup" { capabilities = ["update"] } path "sys/policies/acl/*" { capabilities = ["create", "read", "update", "delete"] }
path "auth/token/accessors" { capabilities = ["list"] }
# Userpass users
path "auth/userpass/users" { capabilities = ["list"] }
path "auth/userpass/users/*" { capabilities = ["create", "read", "update", "delete"] }
# Identity entities, aliases and groups
path "identity/entity/name" { capabilities = ["list"] }
path "identity/entity/name/*" { capabilities = ["create", "read", "update", "delete"] }
path "identity/entity-alias" { capabilities = ["create", "update"] }
path "identity/entity-alias/id/*" { capabilities = ["read", "delete"] }
path "identity/group/name" { capabilities = ["list"] }
path "identity/group/name/*" { capabilities = ["create", "read", "update", "delete"] }
# Tokens: create, list (needs sudo in OpenBao), inspect and revoke by accessor
path "auth/token/create" { capabilities = ["create", "update"] }
path "auth/token/accessors" { capabilities = ["list", "sudo"] }
path "auth/token/lookup-accessor" { capabilities = ["update"] }
path "auth/token/revoke-accessor" { capabilities = ["update"] } path "auth/token/revoke-accessor" { capabilities = ["update"] }
path "identity/*" { capabilities = ["create", "read", "update", "delete", "list"] }
path "sys/mounts" { capabilities = ["read"] } # Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser
path "secret/metadata/*" { capabilities = ["list"] } path "sys/auth" { capabilities = ["read"] }
path "sys/capabilities" { capabilities = ["update"] } path "sys/mounts" { capabilities = ["read"] }
path "secret/metadata/*" { capabilities = ["list"] }
``` ```
Notes:
- Listing token accessors needs `sudo` in OpenBao, so the Tokens tab needs it on `auth/token/accessors`.
- Creating **orphan** tokens (the "Orphan" checkbox) needs `sudo` on `auth/token/create`. It is deliberately not granted above; add `"sudo"` there if you want it.
- If your KV v2 mount is not `secret/`, change `secret/metadata/*`.
- The account can create policies and attach them to identities, which is effectively the power to grant access to anything. Treat it as an administrator.
### Admin login ### Admin login
```sh ```sh
bao policy write envbao-admin envbao-admin.hcl bao policy write envbao-admin docs/envbao-admin.hcl
bao write auth/userpass/users/admin password=... policies=envbao-admin bao write auth/userpass/users/admin password=... token_policies=envbao-admin
# or # or
bao token create -policy=envbao-admin bao token create -policy=envbao-admin
``` ```
@@ -104,7 +145,7 @@ npm run build
This produces a static `dist/` directory. Serve it with any static host, with an SPA fallback to `index.html`. Use HTTPS: the OpenBao token is held in the browser, and browsers block mixed content from an HTTPS page to an HTTP OpenBao. This produces a static `dist/` directory. Serve it with any static host, with an SPA fallback to `index.html`. Use HTTPS: the OpenBao token is held in the browser, and browsers block mixed content from an HTTPS page to an HTTP OpenBao.
nginx: nginx (the bundled [`nginx.conf`](nginx.conf), used by the Docker image, also sets security headers):
```nginx ```nginx
server { server {
@@ -125,19 +166,40 @@ envbao.example.com {
} }
``` ```
The OpenBao URL is entered on the Connect screen. Add the UI's origin to OpenBao's CORS allowed origins (see [CORS](#cors)). The OpenBao URL is entered on the Connect screen; there is no build-time or runtime configuration. Add the UI's origin to OpenBao's CORS allowed origins (see [CORS](#cors)).
CI runs on Gitea Actions (`.gitea/workflows/`): lint, test, build. The bundled `nginx.conf` sends a Content-Security-Policy. Its `connect-src` allows any `http:`/`https:` origin because the OpenBao address is chosen at runtime; if you always use one OpenBao, tighten `connect-src` to that address.
### Container image
```sh
docker build -t envbao-admin .
docker run -p 8080:80 envbao-admin
```
## Development
```sh
npm install
npm run dev # http://localhost:5173
npm test # unit tests
npm run lint
npm run build
BAO_ADDR=http://127.0.0.1:8200 BAO_TOKEN=root npm run test:integration # against a dev OpenBao
```
The integration tests need a dev server with userpass available (they enable it if missing) and a KV v2 mount at `secret/` (the dev-mode default). They create and delete their own uniquely named objects, but run them against a throwaway instance, not a real one.
CI runs on Gitea Actions (`.gitea/workflows/ci.yml`): lint, test and build, plus an integration job against an OpenBao dev container.
## Limitations ## Limitations
- Browser-direct access means CORS must be enabled on OpenBao, and the token lives in the browser (in memory; sessionStorage optional). - **Browser-direct**: CORS must be enabled on OpenBao, and the token lives in the browser's memory (never written to storage). There is no server-side audit trail beyond OpenBao's own audit log.
- No server-side audit trail beyond OpenBao's own audit log. - **Scope**: KV v2 only, and only userpass auth, tokens and identity entities/groups are managed.
- KV v2 only. - **Managed policies**: access is granted by writing one policy per user, entity or group, named `envbao-<kind>-<name>` (for example `envbao-user-alice`). If a managed policy is edited outside EnvBao (for example to add parameter constraints) it becomes read-only in the UI rather than being overwritten. All other policies are shown read-only. Policy names are lower-cased by OpenBao, so identities whose names differ only by case or punctuation would collide; EnvBao detects this and refuses to overwrite.
- Only userpass auth, tokens and identity entities/groups are supported. - **Tokens**: cannot be granted access after creation (OpenBao fixes a token's policies when it is created), so choose their policies when creating them. Tokens created by a token die with it unless created as orphans.
- Access is granted by writing one managed policy per user, entity or group, named `envbao-<kind>-<name>` (for example `envbao-user-alice`). A managed policy that is edited outside EnvBao becomes read-only in the UI. Other policies are always shown read-only. - **Grants** write `<mount>/data/...` rules for read/create/update/delete and `<mount>/metadata/...` for list. `patch`, `sudo` and the KV `delete`/`undelete`/`destroy` sub-paths are not offered.
- Tokens cannot be granted access after creation (OpenBao fixes a token's policies when it is created), so choose their policies when creating them. - **Access model**: follows OpenBao's "most specific path wins" rule. Parameter constraints, control groups, MFA and templated paths are not evaluated (templated paths are approximated), so the access views can over-report for policies that use them; such policies are flagged.
- Grants are KV v2 only: they write `<mount>/data/...` rules for read/create/update/delete and `<mount>/metadata/...` for list. - **Inheritance**: identity→policy edges and the Access panel show *effective* policies, including those a user inherits from an aliased entity and that entity's groups. Nested groups and non-userpass aliases are not followed.
- The access model follows OpenBao's "most specific path wins" rule, so a broader rule never adds to or overrides a more specific one. - **Scale**: the graph and Access panel read every user, entity, group, token and policy on each load, with no pagination, so large instances may be slow.
- Glob and templated policy paths are approximated. - **Sessions**: tokens are not renewed automatically. When one expires you sign in again.
- The graph is not paginated, so large instances may be slow.
+1 -1
View File
@@ -11,7 +11,7 @@ EnvBao needs an admin UI over an OpenBao instance so users/tokens can be created
## Architecture ## Architecture
- `src/api/bao.ts`: typed fetch client (`X-Vault-Token`, base URL config, error mapping). Endpoints: `sys/policies/acl`, `auth/userpass/users`, `auth/token/create|lookup|accessors`, `identity/entity|group`, `sys/mounts`, `secret/metadata` (KV v2), `sys/capabilities`. - `src/api/bao.ts`: typed fetch client (`X-Vault-Token`, base URL config, error mapping). Endpoints: `sys/policies/acl`, `auth/userpass/users`, `auth/token/create|lookup|accessors`, `identity/entity|group`, `sys/mounts`, `secret/metadata` (KV v2), `sys/capabilities`.
- `src/model/`: `buildAccessGraph()` — parses ACL policy HCL path rules into `{path, capabilities}`, joins with identities' attached policies → nodes/edges. Pure and unit-testable. - `src/model/`: `buildAccessGraph()` — parses ACL policy HCL path rules into `{path, capabilities}`, joins with identities' attached policies → nodes/edges. Pure and unit-testable.
- Managed-policy convention: UI generates one policy per (identity, secret path set) named `envbao-<identity>`, so grants are editable via a simple "secret path + capability checkboxes" form rather than raw HCL (raw HCL view available). - Managed-policy convention (as built): one policy per user/entity/group named `envbao-<kind>-<name>`, marked with an `# envbao-owner:` header; tokens cannot be granted to after creation. Originally planned as `envbao-<identity>`, so grants are editable via a simple "secret path + capability checkboxes" form rather than raw HCL (raw HCL view available).
- UI libs: React Router, TanStack Query (server state), `@xyflow/react` (React Flow) + dagre layout for graph, Vitest for tests. - UI libs: React Router, TanStack Query (server state), `@xyflow/react` (React Flow) + dagre layout for graph, Vitest for tests.
## Screens ## Screens
+29
View File
@@ -0,0 +1,29 @@
# Least-privilege policy for the account that uses EnvBao Admin.
# Adjust "secret" if your KV v2 mount has a different path.
# Policies: list, read, create/update and delete (managed `envbao-*` and read-only viewing of the rest)
path "sys/policies/acl" { capabilities = ["list"] }
path "sys/policies/acl/*" { capabilities = ["create", "read", "update", "delete"] }
# Userpass users
path "auth/userpass/users" { capabilities = ["list"] }
path "auth/userpass/users/*" { capabilities = ["create", "read", "update", "delete"] }
# Identity entities, aliases and groups
path "identity/entity/name" { capabilities = ["list"] }
path "identity/entity/name/*" { capabilities = ["create", "read", "update", "delete"] }
path "identity/entity-alias" { capabilities = ["create", "update"] }
path "identity/entity-alias/id/*" { capabilities = ["read", "delete"] }
path "identity/group/name" { capabilities = ["list"] }
path "identity/group/name/*" { capabilities = ["create", "read", "update", "delete"] }
# Tokens: create, list (needs sudo in OpenBao), inspect and revoke by accessor
path "auth/token/create" { capabilities = ["create", "update"] }
path "auth/token/accessors" { capabilities = ["list", "sudo"] }
path "auth/token/lookup-accessor" { capabilities = ["update"] }
path "auth/token/revoke-accessor" { capabilities = ["update"] }
# Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser
path "sys/auth" { capabilities = ["read"] }
path "sys/mounts" { capabilities = ["read"] }
path "secret/metadata/*" { capabilities = ["list"] }
+8
View File
@@ -3,9 +3,17 @@ server {
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html; index index.html;
# The OpenBao address is chosen at runtime, so connect-src cannot be narrowed to one origin.
# Tighten it if you only ever talk to a single OpenBao.
add_header Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http: https:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy no-referrer always;
add_header X-Frame-Options DENY always;
location /assets/ { location /assets/ {
expires 1y; expires 1y;
add_header Cache-Control "public, immutable"; add_header Cache-Control "public, immutable";
add_header X-Content-Type-Options nosniff always;
} }
location / { location / {
+2
View File
@@ -1,5 +1,6 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createBrowserRouter, RouterProvider } from 'react-router' import { createBrowserRouter, RouterProvider } from 'react-router'
import { SessionGuard } from './api/SessionGuard'
import { SessionProvider } from './api/session' import { SessionProvider } from './api/session'
import { routes } from './routes' import { routes } from './routes'
@@ -10,6 +11,7 @@ function App() {
return ( return (
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<SessionProvider> <SessionProvider>
<SessionGuard />
<RouterProvider router={router} /> <RouterProvider router={router} />
</SessionProvider> </SessionProvider>
</QueryClientProvider> </QueryClientProvider>
+19 -3
View File
@@ -1,4 +1,5 @@
import { NavLink, Outlet } from 'react-router' import { Link, NavLink, Outlet } from 'react-router'
import { useSession } from './api/useSession'
const links = [ const links = [
{ to: '/identities', label: 'Identities' }, { to: '/identities', label: 'Identities' },
@@ -6,9 +7,18 @@ const links = [
{ to: '/graph', label: 'Graph' }, { to: '/graph', label: 'Graph' },
] ]
const notices = {
expired: 'Your session has expired or the token was revoked.',
sealed: 'OpenBao has been sealed.',
}
export function Layout() { export function Layout() {
const { notice, client, tokenInfo } = useSession()
return ( return (
<div className="shell"> <div className="shell">
<a href="#main" className="skip-link">
Skip to content
</a>
<nav aria-label="Main"> <nav aria-label="Main">
<strong>EnvBao</strong> <strong>EnvBao</strong>
{links.map((l) => ( {links.map((l) => (
@@ -16,11 +26,17 @@ export function Layout() {
{l.label} {l.label}
</NavLink> </NavLink>
))} ))}
{client && tokenInfo && <span className="whoami">{tokenInfo.display_name || 'token'}</span>}
<NavLink to="/connect" className="connect"> <NavLink to="/connect" className="connect">
Connect {client ? 'Connection' : 'Connect'}
</NavLink> </NavLink>
</nav> </nav>
<main> {notice && (
<div role="alert" className="notice">
{notices[notice]} <Link to="/connect">Sign in again</Link>
</div>
)}
<main id="main" tabIndex={-1}>
<Outlet /> <Outlet />
</main> </main>
</div> </div>
+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'], [403, 'forbidden'],
[404, 'not-found'], [404, 'not-found'],
[500, 'server'], [500, 'server'],
[503, 'unavailable'],
])('maps HTTP %i to %s', async (status, kind) => { ])('maps HTTP %i to %s', async (status, kind) => {
mockFetch(status, { errors: ['nope'] }) mockFetch(status, { errors: ['nope'] })
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toMatchObject({ kind, status }) 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 () => { test('non-JSON success is a bad-response', async () => {
mockFetch(200, '<html>') mockFetch(200, '<html>')
await expect(new BaoClient('http://b').request('GET', 'x')).rejects.toMatchObject({ kind: 'bad-response' }) 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 { export class BaoError extends Error {
readonly kind: BaoErrorKind readonly kind: BaoErrorKind
@@ -49,7 +49,10 @@ export function normaliseBaseUrl(url: string): string {
return trimmed return trimmed
} }
export const REQUEST_TIMEOUT_MS = 15_000
function kindForStatus(status: number): BaoErrorKind { function kindForStatus(status: number): BaoErrorKind {
if (status === 503) return 'unavailable'
if (status === 401) return 'auth' if (status === 401) return 'auth'
if (status === 403) return 'forbidden' if (status === 403) return 'forbidden'
if (status === 404) return 'not-found' if (status === 404) return 'not-found'
@@ -80,8 +83,12 @@ export class BaoClient {
method, method,
headers, headers,
body: body === undefined ? undefined : JSON.stringify(body), 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) throw new BaoError('network', CORS_HINT)
} }
@@ -100,7 +107,9 @@ export class BaoClient {
const message = const message =
res.status === 401 || res.status === 403 res.status === 401 || res.status === 403
? errors.join('; ') || 'Permission denied' ? 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) throw new BaoError(kindForStatus(res.status), message, res.status, errors)
} }
return json as T 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 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. // The token lives only in React state (memory); a page reload logs out.
export function SessionProvider({ children }: { children: ReactNode }) { export function SessionProvider({ children }: { children: ReactNode }) {
const qc = useQueryClient()
const [state, setState] = useState<{ client: BaoClient; tokenInfo: TokenInfo } | null>(null) 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>( const value = useMemo<Session>(
() => ({ () => ({
client: state?.client ?? null, client: state?.client ?? null,
tokenInfo: state?.tokenInfo ?? null, tokenInfo: state?.tokenInfo ?? null,
connect: (client, tokenInfo) => setState({ client, tokenInfo }), notice,
disconnect: () => setState(null), 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> return <SessionContext value={value}>{children}</SessionContext>
} }
+7
View File
@@ -1,11 +1,18 @@
import { createContext, useContext } from 'react' import { createContext, useContext } from 'react'
import type { BaoClient, TokenInfo } from './bao' import type { BaoClient, TokenInfo } from './bao'
/** Why the session ended without the user disconnecting. */
export type SessionNotice = 'expired' | 'sealed'
export interface Session { export interface Session {
client: BaoClient | null client: BaoClient | null
tokenInfo: TokenInfo | 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 connect: (client: BaoClient, tokenInfo: TokenInfo) => void
disconnect: () => void disconnect: () => void
expire: (notice: SessionNotice) => void
} }
export const SessionContext = createContext<Session | null>(null) export const SessionContext = createContext<Session | null>(null)
+14
View File
@@ -0,0 +1,14 @@
import { readFileSync } from 'node:fs'
import { expect, test } from 'vitest'
test('README embeds the tested admin policy verbatim', () => {
const policy = readFileSync('docs/envbao-admin.hcl', 'utf8').trim()
expect(readFileSync('README.md', 'utf8')).toContain(policy)
})
test('README documents every origin the docker-compose setup allows', () => {
const compose = readFileSync('docker-compose.yml', 'utf8')
const origins = /allowed_origins=([^"]+)"/.exec(compose)![1].split(',')
const readme = readFileSync('README.md', 'utf8')
for (const o of origins) expect(readme).toContain(o)
})
+4 -4
View File
@@ -47,7 +47,7 @@ test('shows managed grants and read-only other policies', async () => {
const user = setup() const user = setup()
expect(await screen.findByText('secret/data/app/*')).toBeInTheDocument() expect(await screen.findByText('secret/data/app/*')).toBeInTheDocument()
const other = screen.getByText('default').closest('li')! const other = screen.getByText('default').closest('li')!
await user.click(within(other).getByRole('button', { name: 'View' })) await user.click(within(other).getByRole('button', { name: 'View default' }))
expect(await within(other).findByText(/capabilities/)).toBeInTheDocument() expect(await within(other).findByText(/capabilities/)).toBeInTheDocument()
}) })
@@ -76,9 +76,9 @@ test('revoke asks for confirmation', async () => {
vi.mocked(grants.revokeAccess).mockResolvedValue() vi.mocked(grants.revokeAccess).mockResolvedValue()
const user = setup() const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true) const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Revoke' })) await user.click(await screen.findByRole('button', { name: 'Revoke secret/data/app/*' }))
expect(grants.revokeAccess).not.toHaveBeenCalled() expect(grants.revokeAccess).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Revoke' })) await user.click(screen.getByRole('button', { name: 'Revoke secret/data/app/*' }))
expect(grants.revokeAccess).toHaveBeenCalledWith(client, target, ['secret/data/app/*']) expect(grants.revokeAccess).toHaveBeenCalledWith(client, target, ['secret/data/app/*'])
confirm.mockRestore() confirm.mockRestore()
}) })
@@ -89,7 +89,7 @@ test('a policy edited outside EnvBao is read-only', async () => {
) )
setup() setup()
expect(await screen.findByRole('alert')).toHaveTextContent('changed outside EnvBao') expect(await screen.findByRole('alert')).toHaveTextContent('changed outside EnvBao')
expect(screen.getByRole('button', { name: 'Revoke' })).toBeDisabled() expect(screen.getByRole('button', { name: 'Revoke x' })).toBeDisabled()
expect(screen.queryByRole('form', { name: 'Grant access' })).not.toBeInTheDocument() expect(screen.queryByRole('form', { name: 'Grant access' })).not.toBeInTheDocument()
}) })
+3 -2
View File
@@ -17,7 +17,7 @@ function PolicyView({ client, name }: { client: BaoClient; name: string }) {
return ( return (
<li> <li>
{name}{' '} {name}{' '}
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)}> <button type="button" aria-label={`${open ? 'Hide' : 'View'} ${name}`} aria-expanded={open} onClick={() => setOpen(!open)}>
{open ? 'Hide' : 'View'} {open ? 'Hide' : 'View'}
</button> </button>
{open && <pre>{hcl.isPending ? 'Loading…' : (hcl.data ?? 'Could not read this policy.')}</pre>} {open && <pre>{hcl.isPending ? 'Loading…' : (hcl.data ?? 'Could not read this policy.')}</pre>}
@@ -82,7 +82,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
</p> </p>
)} )}
{s.managed?.grants.length ? ( {s.managed?.grants.length ? (
<table> <table aria-label="Granted by EnvBao">
<thead> <thead>
<tr> <tr>
<th>Path</th> <th>Path</th>
@@ -100,6 +100,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
<td> <td>
<button <button
type="button" type="button"
aria-label={`Revoke ${g.path}`}
disabled={!editable} disabled={!editable}
onClick={() => window.confirm(`Revoke ${g.capabilities.join(', ')} on ${g.path}?`) && revoke.mutate(g.path)} onClick={() => window.confirm(`Revoke ${g.capabilities.join(', ')} on ${g.path}?`) && revoke.mutate(g.path)}
> >
+6 -3
View File
@@ -2,6 +2,7 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { afterEach, expect, test, vi } from 'vitest' import { afterEach, expect, test, vi } from 'vitest'
import { SessionProvider } from '../../api/session' import { SessionProvider } from '../../api/session'
import { Providers } from '../../test/providers'
import { ConnectPage } from './ConnectPage' import { ConnectPage } from './ConnectPage'
const health = { initialized: true, sealed: false, standby: false, version: '2.1.0' } const health = { initialized: true, sealed: false, standby: false, version: '2.1.0' }
@@ -11,9 +12,11 @@ afterEach(() => vi.unstubAllGlobals())
function setup() { function setup() {
render( render(
<SessionProvider> <Providers>
<ConnectPage /> <SessionProvider>
</SessionProvider>, <ConnectPage />
</SessionProvider>
</Providers>,
) )
return userEvent.setup() return userEvent.setup()
} }
+2 -2
View File
@@ -5,8 +5,8 @@ import { useSession } from '../../api/useSession'
type Mode = 'token' | 'userpass' type Mode = 'token' | 'userpass'
export function ConnectPage() { export function ConnectPage() {
const { client, tokenInfo, connect, disconnect } = useSession() const { client, tokenInfo, lastUrl, connect, disconnect } = useSession()
const [url, setUrl] = useState(client?.baseUrl ?? 'http://127.0.0.1:8200') const [url, setUrl] = useState(client?.baseUrl ?? lastUrl ?? 'http://127.0.0.1:8200')
const [mode, setMode] = useState<Mode>('token') const [mode, setMode] = useState<Mode>('token')
const [token, setToken] = useState('') const [token, setToken] = useState('')
const [username, setUsername] = useState('') const [username, setUsername] = useState('')
+8 -4
View File
@@ -3,6 +3,7 @@ import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { addAlias, deleteAlias, deleteEntity, listEntities, saveEntity, userpassAccessor, type Entity } from '../../api/identities' import { addAlias, deleteAlias, deleteEntity, listEntities, saveEntity, userpassAccessor, type Entity } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor' import { AccessEditor } from '../access/AccessEditor'
import { ListState } from '../shared/ListState'
import { PolicyPicker } from '../shared/PolicyPicker' import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft { interface Draft {
@@ -55,8 +56,9 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
return ( return (
<section> <section>
{entities.error && <p role="alert">{entities.error.message}</p>} <ListState query={entities} empty="No entities yet." />
<table> {!!entities.data?.length && (
<table aria-label="Entities">
<thead> <thead>
<tr> <tr>
<th>Entity</th> <th>Entity</th>
@@ -72,14 +74,15 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
<td>{e.aliases.map((a) => a.name).join(', ') || '—'}</td> <td>{e.aliases.map((a) => a.name).join(', ') || '—'}</td>
<td>{e.policies.join(', ') || '—'}</td> <td>{e.policies.join(', ') || '—'}</td>
<td> <td>
<button type="button" onClick={() => setAccessFor(e.name)}> <button type="button" aria-label={`Access ${e.name}`} onClick={() => setAccessFor(e.name)}>
Access Access
</button>{' '} </button>{' '}
<button type="button" onClick={() => setDraft({ name: e.name, policies: e.policies, isNew: false, entity: e })}> <button type="button" aria-label={`Edit ${e.name}`} onClick={() => setDraft({ name: e.name, policies: e.policies, isNew: false, entity: e })}>
Edit Edit
</button>{' '} </button>{' '}
<button <button
type="button" type="button"
aria-label={`Delete ${e.name}`}
onClick={() => window.confirm(`Delete entity "${e.name}" and its aliases?`) && remove.mutate(e.name)} onClick={() => window.confirm(`Delete entity "${e.name}" and its aliases?`) && remove.mutate(e.name)}
> >
Delete Delete
@@ -89,6 +92,7 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
))} ))}
</tbody> </tbody>
</table> </table>
)}
{remove.error && <p role="alert">{remove.error.message}</p>} {remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && ( {!draft && (
<button type="button" onClick={() => setDraft({ name: '', policies: [], isNew: true })}> <button type="button" onClick={() => setDraft({ name: '', policies: [], isNew: true })}>
+8 -4
View File
@@ -3,6 +3,7 @@ import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/identities' import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor' import { AccessEditor } from '../access/AccessEditor'
import { ListState } from '../shared/ListState'
import { PolicyPicker } from '../shared/PolicyPicker' import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft { interface Draft {
@@ -38,8 +39,9 @@ export function GroupsTab({ client }: { client: BaoClient }) {
return ( return (
<section> <section>
{groups.error && <p role="alert">{groups.error.message}</p>} <ListState query={groups} empty="No groups yet." />
<table> {!!groups.data?.length && (
<table aria-label="Groups">
<thead> <thead>
<tr> <tr>
<th>Group</th> <th>Group</th>
@@ -55,16 +57,17 @@ export function GroupsTab({ client }: { client: BaoClient }) {
<td>{g.member_entity_ids.map(nameOf).join(', ') || '—'}</td> <td>{g.member_entity_ids.map(nameOf).join(', ') || '—'}</td>
<td>{g.policies.join(', ') || '—'}</td> <td>{g.policies.join(', ') || '—'}</td>
<td> <td>
<button type="button" onClick={() => setAccessFor(g.name)}> <button type="button" aria-label={`Access ${g.name}`} onClick={() => setAccessFor(g.name)}>
Access Access
</button>{' '} </button>{' '}
<button <button
type="button" type="button"
aria-label={`Edit ${g.name}`}
onClick={() => setDraft({ name: g.name, policies: g.policies, members: g.member_entity_ids, isNew: false })} onClick={() => setDraft({ name: g.name, policies: g.policies, members: g.member_entity_ids, isNew: false })}
> >
Edit Edit
</button>{' '} </button>{' '}
<button type="button" onClick={() => window.confirm(`Delete group "${g.name}"?`) && remove.mutate(g.name)}> <button type="button" aria-label={`Delete ${g.name}`} onClick={() => window.confirm(`Delete group "${g.name}"?`) && remove.mutate(g.name)}>
Delete Delete
</button> </button>
</td> </td>
@@ -72,6 +75,7 @@ export function GroupsTab({ client }: { client: BaoClient }) {
))} ))}
</tbody> </tbody>
</table> </table>
)}
{remove.error && <p role="alert">{remove.error.message}</p>} {remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && ( {!draft && (
<button type="button" onClick={() => setDraft({ name: '', policies: [], members: [], isNew: true })}> <button type="button" onClick={() => setDraft({ name: '', policies: [], members: [], isNew: true })}>
+3 -1
View File
@@ -18,15 +18,17 @@ export function IdentitiesPage() {
<> <>
<div role="tablist" className="tabs"> <div role="tablist" className="tabs">
{tabs.map((t) => ( {tabs.map((t) => (
<button key={t} type="button" role="tab" aria-selected={tab === t} onClick={() => setTab(t)}> <button key={t} type="button" role="tab" id={`tab-${t}`} aria-selected={tab === t} aria-controls="identities-panel" onClick={() => setTab(t)}>
{t} {t}
</button> </button>
))} ))}
</div> </div>
<div role="tabpanel" id="identities-panel" aria-labelledby={`tab-${tab}`}>
{tab === 'Users' && <UsersTab client={client} />} {tab === 'Users' && <UsersTab client={client} />}
{tab === 'Entities' && <EntitiesTab client={client} />} {tab === 'Entities' && <EntitiesTab client={client} />}
{tab === 'Groups' && <GroupsTab client={client} />} {tab === 'Groups' && <GroupsTab client={client} />}
{tab === 'Tokens' && <TokensTab client={client} />} {tab === 'Tokens' && <TokensTab client={client} />}
</div>
</> </>
)} )}
</RequireConnection> </RequireConnection>
+2 -2
View File
@@ -72,9 +72,9 @@ test('revoke requires confirmation', async () => {
vi.mocked(api.revokeToken).mockResolvedValue() vi.mocked(api.revokeToken).mockResolvedValue()
const user = setup() const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true) const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Revoke' })) await user.click(await screen.findByRole('button', { name: 'Revoke token-ci' }))
expect(api.revokeToken).not.toHaveBeenCalled() expect(api.revokeToken).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Revoke' })) await user.click(screen.getByRole('button', { name: 'Revoke token-ci' }))
expect(api.revokeToken).toHaveBeenCalledWith(client, 'acc-aaaaaaaa') expect(api.revokeToken).toHaveBeenCalledWith(client, 'acc-aaaaaaaa')
confirm.mockRestore() confirm.mockRestore()
}) })
+6 -2
View File
@@ -3,6 +3,7 @@ import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { createToken, listTokens, revokeToken, type CreatedToken } from '../../api/tokens' import { createToken, listTokens, revokeToken, type CreatedToken } from '../../api/tokens'
import { useSession } from '../../api/useSession' import { useSession } from '../../api/useSession'
import { ListState } from '../shared/ListState'
import { PolicyPicker } from '../shared/PolicyPicker' import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft { interface Draft {
@@ -76,8 +77,9 @@ export function TokensTab({ client }: { client: BaoClient }) {
</button> </button>
</div> </div>
)} )}
{tokens.error && <p role="alert">{tokens.error.message}</p>} <ListState query={tokens} empty="No tokens." />
<table> {!!tokens.data?.length && (
<table aria-label="Tokens">
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
@@ -104,6 +106,7 @@ export function TokensTab({ client }: { client: BaoClient }) {
<td> <td>
<button <button
type="button" type="button"
aria-label={`Revoke ${t.display_name || t.accessor}`}
disabled={isSelf} disabled={isSelf}
title={isSelf ? 'This is the token you are signed in with' : undefined} title={isSelf ? 'This is the token you are signed in with' : undefined}
onClick={() => onClick={() =>
@@ -119,6 +122,7 @@ export function TokensTab({ client }: { client: BaoClient }) {
})} })}
</tbody> </tbody>
</table> </table>
)}
{revoke.error && <p role="alert">{revoke.error.message}</p>} {revoke.error && <p role="alert">{revoke.error.message}</p>}
{!draft && ( {!draft && (
<button type="button" onClick={() => setDraft(empty)}> <button type="button" onClick={() => setDraft(empty)}>
+3 -3
View File
@@ -45,7 +45,7 @@ test('creates a user with selected policies', async () => {
test('editing keeps the username fixed and the password optional', async () => { test('editing keeps the username fixed and the password optional', async () => {
const user = setup() const user = setup()
await user.click(await screen.findByRole('button', { name: 'Edit' })) await user.click(await screen.findByRole('button', { name: 'Edit alice' }))
expect(screen.getByLabelText('Username')).toBeDisabled() expect(screen.getByLabelText('Username')).toBeDisabled()
await user.click(await screen.findByLabelText('default')) await user.click(await screen.findByLabelText('default'))
await user.click(screen.getByRole('button', { name: 'Save' })) await user.click(screen.getByRole('button', { name: 'Save' }))
@@ -55,9 +55,9 @@ test('editing keeps the username fixed and the password optional', async () => {
test('delete requires confirmation', async () => { test('delete requires confirmation', async () => {
const user = setup() const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true) const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Delete' })) await user.click(await screen.findByRole('button', { name: 'Delete alice' }))
expect(api.deleteUser).not.toHaveBeenCalled() expect(api.deleteUser).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Delete' })) await user.click(screen.getByRole('button', { name: 'Delete alice' }))
expect(api.deleteUser).toHaveBeenCalledWith(client, 'alice') expect(api.deleteUser).toHaveBeenCalledWith(client, 'alice')
confirm.mockRestore() confirm.mockRestore()
}) })
+8 -4
View File
@@ -3,6 +3,7 @@ import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { deleteUser, listUsers, saveUser } from '../../api/identities' import { deleteUser, listUsers, saveUser } from '../../api/identities'
import { AccessEditor } from '../access/AccessEditor' import { AccessEditor } from '../access/AccessEditor'
import { ListState } from '../shared/ListState'
import { PolicyPicker } from '../shared/PolicyPicker' import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft { interface Draft {
@@ -40,8 +41,9 @@ export function UsersTab({ client }: { client: BaoClient }) {
return ( return (
<section> <section>
{users.error && <p role="alert">{users.error.message}</p>} <ListState query={users} empty="No users yet." />
<table> {!!users.data?.length && (
<table aria-label="Users">
<thead> <thead>
<tr> <tr>
<th>User</th> <th>User</th>
@@ -55,14 +57,15 @@ export function UsersTab({ client }: { client: BaoClient }) {
<td>{u.name}</td> <td>{u.name}</td>
<td>{u.policies.join(', ') || '—'}</td> <td>{u.policies.join(', ') || '—'}</td>
<td> <td>
<button type="button" onClick={() => setAccessFor(u.name)}> <button type="button" aria-label={`Access ${u.name}`} onClick={() => setAccessFor(u.name)}>
Access Access
</button>{' '} </button>{' '}
<button type="button" onClick={() => setDraft({ ...u, password: '', ttl: u.ttl ? `${u.ttl}s` : '', isNew: false })}> <button type="button" aria-label={`Edit ${u.name}`} onClick={() => setDraft({ ...u, password: '', ttl: u.ttl ? `${u.ttl}s` : '', isNew: false })}>
Edit Edit
</button>{' '} </button>{' '}
<button <button
type="button" type="button"
aria-label={`Delete ${u.name}`}
onClick={() => window.confirm(`Delete user "${u.name}"? This cannot be undone.`) && remove.mutate(u.name)} onClick={() => window.confirm(`Delete user "${u.name}"? This cannot be undone.`) && remove.mutate(u.name)}
> >
Delete Delete
@@ -72,6 +75,7 @@ export function UsersTab({ client }: { client: BaoClient }) {
))} ))}
</tbody> </tbody>
</table> </table>
)}
{remove.error && <p role="alert">{remove.error.message}</p>} {remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && ( {!draft && (
<button type="button" onClick={() => setDraft(empty)}> <button type="button" onClick={() => setDraft(empty)}>
+13
View File
@@ -0,0 +1,13 @@
interface Query {
isPending: boolean
error: Error | null
data?: unknown[]
}
/** Loading / error / empty feedback for a list. Renders nothing once there is data to show. */
export function ListState({ query, empty }: { query: Query; empty: string }) {
if (query.isPending) return <p role="status">Loading…</p>
if (query.error) return <p role="alert">{query.error.message}</p>
if (query.data?.length === 0) return <p>{empty}</p>
return null
}
+32
View File
@@ -184,3 +184,35 @@ pre {
.gnode-selected { .gnode-selected {
box-shadow: 0 0 0 3px #d4a017; box-shadow: 0 0 0 3px #d4a017;
} }
.skip-link {
position: absolute;
left: -9999px;
}
.skip-link:focus {
left: 0.5rem;
top: 0.5rem;
z-index: 10;
background: Canvas;
padding: 0.5rem;
}
.notice {
padding: 0.6rem 1rem;
background: color-mix(in srgb, #d4a017 25%, transparent);
border-bottom: 1px solid #d4a017;
}
.whoami {
opacity: 0.7;
margin-left: auto;
}
.whoami + .connect {
margin-left: 0;
}
main:focus {
outline: none;
}
+11 -6
View File
@@ -2,6 +2,7 @@ import { render, screen } from '@testing-library/react'
import { createMemoryRouter, RouterProvider } from 'react-router' import { createMemoryRouter, RouterProvider } from 'react-router'
import { expect, test } from 'vitest' import { expect, test } from 'vitest'
import { SessionProvider } from './api/session' import { SessionProvider } from './api/session'
import { Providers } from './test/providers'
import { routes } from './routes' import { routes } from './routes'
test.each([ test.each([
@@ -12,9 +13,11 @@ test.each([
])('renders %s', (path, heading) => { ])('renders %s', (path, heading) => {
const router = createMemoryRouter(routes, { initialEntries: [path] }) const router = createMemoryRouter(routes, { initialEntries: [path] })
render( render(
<SessionProvider> <Providers>
<RouterProvider router={router} /> <SessionProvider>
</SessionProvider>, <RouterProvider router={router} />
</SessionProvider>
</Providers>,
) )
expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument() expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument()
}) })
@@ -22,9 +25,11 @@ test.each([
test('redirects / to identities', () => { test('redirects / to identities', () => {
const router = createMemoryRouter(routes, { initialEntries: ['/'] }) const router = createMemoryRouter(routes, { initialEntries: ['/'] })
render( render(
<SessionProvider> <Providers>
<RouterProvider router={router} /> <SessionProvider>
</SessionProvider>, <RouterProvider router={router} />
</SessionProvider>
</Providers>,
) )
expect(screen.getByRole('heading', { name: 'Identities' })).toBeInTheDocument() expect(screen.getByRole('heading', { name: 'Identities' })).toBeInTheDocument()
}) })
+7
View File
@@ -0,0 +1,7 @@
import { QueryClientProvider, type QueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { testQueryClient } from './queryClient'
export function Providers({ children, client }: { children: ReactNode; client?: QueryClient }) {
return <QueryClientProvider client={client ?? testQueryClient()}>{children}</QueryClientProvider>
}
+3
View File
@@ -0,0 +1,3 @@
import { QueryClient } from '@tanstack/react-query'
export const testQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } })