Add identity management: userpass users, entities with aliases, groups
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a13d2cb04a
commit
4706014dc2
10 files changed
+733
-1
No files matched your search
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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)}</>
|
||||
}
|
||||
Reference in new issue
Block a user