Add identity management: userpass users, entities with aliases, groups
CI / integration (push) Successful in 10s
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:15:38 +01:00
1 parent a13d2cb04a
commit 4706014dc2
10 files changed
+733 -1

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { beforeAll, describe, expect, test } from 'vitest'
import { BaoClient } from './bao'
import * as api from './identities'
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const suffix = Math.random().toString(36).slice(2, 8)
beforeAll(async () => {
const mounts = await client.request<{ data: Record<string, { type: string }> }>('GET', 'sys/auth')
if (!Object.values(mounts.data).some((m) => m.type === 'userpass')) {
await client.request('POST', 'sys/auth/userpass', { type: 'userpass' })
}
})
describe('identity API against a dev OpenBao', () => {
test('userpass user CRUD', async () => {
const name = `it-user-${suffix}`
await api.saveUser(client, { name, password: 'pw-123456', policies: ['default'], ttl: '1h' })
expect((await api.listUsers(client)).find((u) => u.name === name)).toMatchObject({
policies: ['default'],
ttl: 3600,
})
// edit without a password keeps the old one and updates policies
await api.saveUser(client, { name, policies: ['default', 'it-extra'] })
expect((await api.readUser(client, name)).policies).toEqual(['default', 'it-extra'])
const login = await client.loginUserpass(name, 'pw-123456')
expect(login.token).toBeTruthy()
await api.deleteUser(client, name)
expect((await api.listUsers(client)).some((u) => u.name === name)).toBe(false)
})
test('entity with alias, and group membership', async () => {
const user = `it-alias-${suffix}`
const ename = `it-entity-${suffix}`
const gname = `it-group-${suffix}`
await api.saveUser(client, { name: user, password: 'pw-123456', policies: [] })
await api.saveEntity(client, { name: ename, policies: ['default'] })
const entity = await api.readEntity(client, ename)
const accessor = await api.userpassAccessor(client)
expect(accessor).toBeTruthy()
await api.addAlias(client, { name: user, entityId: entity.id, mountAccessor: accessor! })
const withAlias = await api.readEntity(client, ename)
expect(withAlias.aliases).toHaveLength(1)
expect(withAlias.aliases[0].name).toBe(user)
await api.saveGroup(client, { name: gname, policies: ['default'], memberEntityIds: [entity.id] })
expect((await api.listGroups(client)).find((g) => g.name === gname)?.member_entity_ids).toEqual([entity.id])
await api.deleteGroup(client, gname)
await api.deleteAlias(client, withAlias.aliases[0].id)
expect((await api.readEntity(client, ename)).aliases).toHaveLength(0)
await api.deleteEntity(client, ename)
await api.deleteUser(client, user)
expect((await api.listEntities(client)).some((e) => e.name === ename)).toBe(false)
})
})
+139
View File
@@ -0,0 +1,139 @@
import type { BaoClient } from './bao'
const enc = encodeURIComponent
export interface UserpassUser {
name: string
policies: string[]
ttl: number
}
export interface EntityAlias {
id: string
name: string
mount_accessor: string
mount_path: string
}
export interface Entity {
id: string
name: string
policies: string[]
disabled: boolean
aliases: EntityAlias[]
}
export interface Group {
id: string
name: string
policies: string[]
member_entity_ids: string[]
}
export async function listPolicyNames(c: BaoClient): Promise<string[]> {
return c.list('sys/policies/acl')
}
// ---- userpass users ----
export async function listUsers(c: BaoClient): Promise<UserpassUser[]> {
const names = await c.list('auth/userpass/users')
return Promise.all(names.map((n) => readUser(c, n)))
}
export async function readUser(c: BaoClient, name: string): Promise<UserpassUser> {
const res = await c.request<{ data: { token_policies?: string[]; token_ttl?: number } }>(
'GET',
`auth/userpass/users/${enc(name)}`,
)
return { name, policies: res.data.token_policies ?? [], ttl: res.data.token_ttl ?? 0 }
}
/** `password` is omitted on edit to keep the existing one. */
export async function saveUser(
c: BaoClient,
user: { name: string; password?: string; policies: string[]; ttl?: string },
): Promise<void> {
await c.request('POST', `auth/userpass/users/${enc(user.name)}`, {
...(user.password ? { password: user.password } : {}),
token_policies: user.policies,
...(user.ttl ? { token_ttl: user.ttl } : {}),
})
}
export async function deleteUser(c: BaoClient, name: string): Promise<void> {
await c.request('DELETE', `auth/userpass/users/${enc(name)}`)
}
/** Mount accessor of the userpass auth method, needed to create entity aliases. */
export async function userpassAccessor(c: BaoClient): Promise<string | null> {
const res = await c.request<{ data: Record<string, { accessor: string; type: string }> }>('GET', 'sys/auth')
return Object.values(res.data).find((m) => m.type === 'userpass')?.accessor ?? null
}
// ---- entities ----
export async function listEntities(c: BaoClient): Promise<Entity[]> {
const names = await c.list('identity/entity/name')
return Promise.all(names.map((n) => readEntity(c, n)))
}
export async function readEntity(c: BaoClient, name: string): Promise<Entity> {
const res = await c.request<{ data: Partial<Entity> & { id: string } }>('GET', `identity/entity/name/${enc(name)}`)
const d = res.data
return { id: d.id, name, policies: d.policies ?? [], disabled: d.disabled ?? false, aliases: d.aliases ?? [] }
}
export async function saveEntity(
c: BaoClient,
e: { name: string; policies: string[]; disabled?: boolean },
): Promise<void> {
await c.request('POST', `identity/entity/name/${enc(e.name)}`, { policies: e.policies, disabled: e.disabled ?? false })
}
export async function deleteEntity(c: BaoClient, name: string): Promise<void> {
await c.request('DELETE', `identity/entity/name/${enc(name)}`)
}
export async function addAlias(
c: BaoClient,
a: { name: string; entityId: string; mountAccessor: string },
): Promise<void> {
await c.request('POST', 'identity/entity-alias', {
name: a.name,
canonical_id: a.entityId,
mount_accessor: a.mountAccessor,
})
}
export async function deleteAlias(c: BaoClient, aliasId: string): Promise<void> {
await c.request('DELETE', `identity/entity-alias/id/${enc(aliasId)}`)
}
// ---- groups ----
export async function listGroups(c: BaoClient): Promise<Group[]> {
const names = await c.list('identity/group/name')
return Promise.all(names.map((n) => readGroup(c, n)))
}
export async function readGroup(c: BaoClient, name: string): Promise<Group> {
const res = await c.request<{ data: Partial<Group> & { id: string } }>('GET', `identity/group/name/${enc(name)}`)
const d = res.data
return { id: d.id, name, policies: d.policies ?? [], member_entity_ids: d.member_entity_ids ?? [] }
}
export async function saveGroup(
c: BaoClient,
g: { name: string; policies: string[]; memberEntityIds: string[] },
): Promise<void> {
await c.request('POST', `identity/group/name/${enc(g.name)}`, {
type: 'internal',
policies: g.policies,
member_entity_ids: g.memberEntityIds,
})
}
export async function deleteGroup(c: BaoClient, name: string): Promise<void> {
await c.request('DELETE', `identity/group/name/${enc(name)}`)
}
+138
View File
@@ -0,0 +1,138 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { addAlias, deleteAlias, deleteEntity, listEntities, saveEntity, userpassAccessor, type Entity } from '../../api/identities'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
name: string
policies: string[]
isNew: boolean
entity?: Entity
}
export function EntitiesTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const [aliasName, setAliasName] = useState('')
const refresh = () => qc.invalidateQueries({ queryKey: ['entities'] })
const save = useMutation({
mutationFn: (d: Draft) => saveEntity(client, { name: d.name, policies: d.policies }),
onSuccess: () => {
setDraft(null)
return refresh()
},
})
const remove = useMutation({ mutationFn: (name: string) => deleteEntity(client, name), onSuccess: refresh })
const attach = useMutation({
mutationFn: async ({ entity, name }: { entity: Entity; name: string }) => {
const accessor = await userpassAccessor(client)
if (!accessor) throw new Error('The userpass auth method is not enabled.')
await addAlias(client, { name, entityId: entity.id, mountAccessor: accessor })
},
onSuccess: () => {
setAliasName('')
setDraft(null)
return refresh()
},
})
const detach = useMutation({
mutationFn: (aliasId: string) => deleteAlias(client, aliasId),
onSuccess: () => {
setDraft(null)
return refresh()
},
})
function submit(e: FormEvent) {
e.preventDefault()
if (draft) save.mutate(draft)
}
return (
<section>
{entities.error && <p role="alert">{entities.error.message}</p>}
<table>
<thead>
<tr>
<th>Entity</th>
<th>Aliases</th>
<th>Policies</th>
<th />
</tr>
</thead>
<tbody>
{entities.data?.map((e) => (
<tr key={e.id}>
<td>{e.name}</td>
<td>{e.aliases.map((a) => a.name).join(', ') || '—'}</td>
<td>{e.policies.join(', ') || '—'}</td>
<td>
<button type="button" onClick={() => setDraft({ name: e.name, policies: e.policies, isNew: false, entity: e })}>
Edit
</button>{' '}
<button
type="button"
onClick={() => window.confirm(`Delete entity "${e.name}" and its aliases?`) && remove.mutate(e.name)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
{remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && (
<button type="button" onClick={() => setDraft({ name: '', policies: [], isNew: true })}>
New entity
</button>
)}
{draft && (
<form onSubmit={submit} aria-label={draft.isNew ? 'New entity' : `Edit ${draft.name}`}>
<label>
Name
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => setDraft({ ...draft, name: e.target.value })} required />
</label>
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
{save.error && <p role="alert">{save.error.message}</p>}
<div>
<button type="submit" disabled={save.isPending}>
Save
</button>{' '}
<button type="button" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
{draft.entity && (
<fieldset>
<legend>Userpass aliases</legend>
{draft.entity.aliases.map((a) => (
<div key={a.id}>
{a.name}{' '}
<button type="button" onClick={() => window.confirm(`Remove alias "${a.name}"?`) && detach.mutate(a.id)}>
Remove
</button>
</div>
))}
<label>
Link userpass user
<input value={aliasName} onChange={(e) => setAliasName(e.target.value)} placeholder="username" />
</label>
<button
type="button"
disabled={!aliasName || attach.isPending}
onClick={() => draft.entity && attach.mutate({ entity: draft.entity, name: aliasName })}
>
Link
</button>
{(attach.error || detach.error) && <p role="alert">{(attach.error ?? detach.error)?.message}</p>}
</fieldset>
)}
</form>
)}
</section>
)
}
+112
View File
@@ -0,0 +1,112 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/identities'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
name: string
policies: string[]
members: string[]
isNew: boolean
}
export function GroupsTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const groups = useQuery({ queryKey: ['groups'], queryFn: () => listGroups(client) })
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const refresh = () => qc.invalidateQueries({ queryKey: ['groups'] })
const nameOf = (id: string) => entities.data?.find((e) => e.id === id)?.name ?? id
const save = useMutation({
mutationFn: (d: Draft) => saveGroup(client, { name: d.name, policies: d.policies, memberEntityIds: d.members }),
onSuccess: () => {
setDraft(null)
return refresh()
},
})
const remove = useMutation({ mutationFn: (name: string) => deleteGroup(client, name), onSuccess: refresh })
function submit(e: FormEvent) {
e.preventDefault()
if (draft) save.mutate(draft)
}
return (
<section>
{groups.error && <p role="alert">{groups.error.message}</p>}
<table>
<thead>
<tr>
<th>Group</th>
<th>Members</th>
<th>Policies</th>
<th />
</tr>
</thead>
<tbody>
{groups.data?.map((g) => (
<tr key={g.id}>
<td>{g.name}</td>
<td>{g.member_entity_ids.map(nameOf).join(', ') || '—'}</td>
<td>{g.policies.join(', ') || '—'}</td>
<td>
<button
type="button"
onClick={() => setDraft({ name: g.name, policies: g.policies, members: g.member_entity_ids, isNew: false })}
>
Edit
</button>{' '}
<button type="button" onClick={() => window.confirm(`Delete group "${g.name}"?`) && remove.mutate(g.name)}>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
{remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && (
<button type="button" onClick={() => setDraft({ name: '', policies: [], members: [], isNew: true })}>
New group
</button>
)}
{draft && (
<form onSubmit={submit} aria-label={draft.isNew ? 'New group' : `Edit ${draft.name}`}>
<label>
Name
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => setDraft({ ...draft, name: e.target.value })} required />
</label>
<fieldset>
<legend>Member entities</legend>
{entities.data?.map((e) => (
<label key={e.id} className="check">
<input
type="checkbox"
checked={draft.members.includes(e.id)}
onChange={(ev) =>
setDraft({ ...draft, members: ev.target.checked ? [...draft.members, e.id] : draft.members.filter((m) => m !== e.id) })
}
/>{' '}
{e.name}
</label>
))}
{entities.data?.length === 0 && <p>No entities yet.</p>}
</fieldset>
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
{save.error && <p role="alert">{save.error.message}</p>}
<div>
<button type="submit" disabled={save.isPending}>
Save
</button>{' '}
<button type="button" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
</section>
)
}
+31 -1
View File
@@ -1,3 +1,33 @@
import { useState } from 'react'
import { RequireConnection } from '../shared/RequireConnection'
import { EntitiesTab } from './EntitiesTab'
import { GroupsTab } from './GroupsTab'
import { UsersTab } from './UsersTab'
const tabs = ['Users', 'Entities', 'Groups'] as const
type Tab = (typeof tabs)[number]
export function IdentitiesPage() {
return <h1>Identities</h1>
const [tab, setTab] = useState<Tab>('Users')
return (
<section>
<h1>Identities</h1>
<RequireConnection>
{(client) => (
<>
<div role="tablist" className="tabs">
{tabs.map((t) => (
<button key={t} type="button" role="tab" aria-selected={tab === t} onClick={() => setTab(t)}>
{t}
</button>
))}
</div>
{tab === 'Users' && <UsersTab client={client} />}
{tab === 'Entities' && <EntitiesTab client={client} />}
{tab === 'Groups' && <GroupsTab client={client} />}
</>
)}
</RequireConnection>
</section>
)
}
+69
View File
@@ -0,0 +1,69 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao'
import * as api from '../../api/identities'
import { UsersTab } from './UsersTab'
vi.mock('../../api/identities')
const client = new BaoClient('http://b', 't')
beforeEach(() => {
vi.mocked(api.listUsers).mockResolvedValue([{ name: 'alice', policies: ['dev'], ttl: 0 }])
vi.mocked(api.listPolicyNames).mockResolvedValue(['default', 'dev'])
vi.mocked(api.saveUser).mockResolvedValue()
vi.mocked(api.deleteUser).mockResolvedValue()
})
afterEach(() => vi.resetAllMocks())
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<UsersTab client={client} />
</QueryClientProvider>,
)
return userEvent.setup()
}
test('lists users', async () => {
setup()
const row = (await screen.findByText('alice')).closest('tr')!
expect(within(row).getByText('dev')).toBeInTheDocument()
})
test('creates a user with selected policies', async () => {
const user = setup()
await user.click(await screen.findByRole('button', { name: 'New user' }))
await user.type(screen.getByLabelText('Username'), 'bob')
await user.type(screen.getByLabelText('Password'), 'pw')
await user.click(await screen.findByLabelText('dev'))
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(api.saveUser).toHaveBeenCalledWith(client, { name: 'bob', password: 'pw', policies: ['dev'], ttl: '' })
})
test('editing keeps the username fixed and the password optional', async () => {
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Edit' }))
expect(screen.getByLabelText('Username')).toBeDisabled()
await user.click(await screen.findByLabelText('default'))
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(api.saveUser).toHaveBeenCalledWith(client, { name: 'alice', password: '', policies: ['dev', 'default'], ttl: '' })
})
test('delete requires confirmation', async () => {
const user = setup()
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
await user.click(await screen.findByRole('button', { name: 'Delete' }))
expect(api.deleteUser).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Delete' }))
expect(api.deleteUser).toHaveBeenCalledWith(client, 'alice')
confirm.mockRestore()
})
test('shows API errors', async () => {
vi.mocked(api.listUsers).mockRejectedValue(new Error('permission denied'))
setup()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+111
View File
@@ -0,0 +1,111 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { deleteUser, listUsers, saveUser } from '../../api/identities'
import { PolicyPicker } from '../shared/PolicyPicker'
interface Draft {
name: string
password: string
policies: string[]
ttl: string
isNew: boolean
}
const empty: Draft = { name: '', password: '', policies: [], ttl: '', isNew: true }
export function UsersTab({ client }: { client: BaoClient }) {
const qc = useQueryClient()
const users = useQuery({ queryKey: ['users'], queryFn: () => listUsers(client) })
const [draft, setDraft] = useState<Draft | null>(null)
const save = useMutation({
mutationFn: (d: Draft) => saveUser(client, { name: d.name, password: d.password, policies: d.policies, ttl: d.ttl }),
onSuccess: () => {
setDraft(null)
return qc.invalidateQueries({ queryKey: ['users'] })
},
})
const remove = useMutation({
mutationFn: (name: string) => deleteUser(client, name),
onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }),
})
function submit(e: FormEvent) {
e.preventDefault()
if (draft) save.mutate(draft)
}
return (
<section>
{users.error && <p role="alert">{users.error.message}</p>}
<table>
<thead>
<tr>
<th>User</th>
<th>Policies</th>
<th />
</tr>
</thead>
<tbody>
{users.data?.map((u) => (
<tr key={u.name}>
<td>{u.name}</td>
<td>{u.policies.join(', ') || '—'}</td>
<td>
<button type="button" onClick={() => setDraft({ ...u, password: '', ttl: u.ttl ? `${u.ttl}s` : '', isNew: false })}>
Edit
</button>{' '}
<button
type="button"
onClick={() => window.confirm(`Delete user "${u.name}"? This cannot be undone.`) && remove.mutate(u.name)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
{remove.error && <p role="alert">{remove.error.message}</p>}
{!draft && (
<button type="button" onClick={() => setDraft(empty)}>
New user
</button>
)}
{draft && (
<form onSubmit={submit} aria-label={draft.isNew ? 'New user' : `Edit ${draft.name}`}>
<label>
Username
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => setDraft({ ...draft, name: e.target.value })} required />
</label>
<label>
Password
<input
type="password"
value={draft.password}
onChange={(e) => setDraft({ ...draft, password: e.target.value })}
required={draft.isNew}
placeholder={draft.isNew ? '' : 'Leave blank to keep'}
autoComplete="new-password"
/>
</label>
<label>
Token TTL
<input value={draft.ttl} onChange={(e) => setDraft({ ...draft, ttl: e.target.value })} placeholder="e.g. 1h (optional)" />
</label>
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
{save.error && <p role="alert">{save.error.message}</p>}
<div>
<button type="submit" disabled={save.isPending}>
Save
</button>{' '}
<button type="button" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
</section>
)
}
+31
View File
@@ -0,0 +1,31 @@
import { useQuery } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { listPolicyNames } from '../../api/identities'
interface Props {
client: BaoClient
value: string[]
onChange: (policies: string[]) => void
}
export function PolicyPicker({ client, value, onChange }: Props) {
const { data, error } = useQuery({ queryKey: ['policies'], queryFn: () => listPolicyNames(client) })
// Keep policies that are attached but no longer exist selectable, so editing doesn't drop them silently.
const names = [...new Set([...(data ?? []), ...value])].filter((n) => n !== 'root').sort()
return (
<fieldset>
<legend>Policies</legend>
{error && <p role="alert">Could not load policies: {error.message}</p>}
{names.map((n) => (
<label key={n} className="check">
<input
type="checkbox"
checked={value.includes(n)}
onChange={(e) => onChange(e.target.checked ? [...value, n] : value.filter((v) => v !== n))}
/>{' '}
{n}
</label>
))}
</fieldset>
)
}
+16
View File
@@ -0,0 +1,16 @@
import type { ReactNode } from 'react'
import { Link } from 'react-router'
import type { BaoClient } from '../../api/bao'
import { useSession } from '../../api/useSession'
export function RequireConnection({ children }: { children: (client: BaoClient) => ReactNode }) {
const { client } = useSession()
if (!client) {
return (
<p>
Not connected. <Link to="/connect">Connect to OpenBao</Link> first.
</p>
)
}
return <>{children(client)}</>
}
+27
View File
@@ -48,3 +48,30 @@ form label {
[role='alert'] {
color: #c0392b;
}
table {
border-collapse: collapse;
margin-bottom: 1rem;
}
th,
td {
text-align: left;
padding: 0.35rem 0.75rem;
border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
}
.tabs {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}
.tabs [aria-selected='true'] {
font-weight: 600;
text-decoration: underline;
}
label.check {
display: block;
}