diff --git a/src/api/identities.integration.test.ts b/src/api/identities.integration.test.ts new file mode 100644 index 0000000..f5a4896 --- /dev/null +++ b/src/api/identities.integration.test.ts @@ -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 }>('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) + }) +}) diff --git a/src/api/identities.ts b/src/api/identities.ts new file mode 100644 index 0000000..ec1eb67 --- /dev/null +++ b/src/api/identities.ts @@ -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 { + return c.list('sys/policies/acl') +} + +// ---- userpass users ---- + +export async function listUsers(c: BaoClient): Promise { + 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 { + 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 { + 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 { + 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 { + const res = await c.request<{ data: Record }>('GET', 'sys/auth') + return Object.values(res.data).find((m) => m.type === 'userpass')?.accessor ?? null +} + +// ---- entities ---- + +export async function listEntities(c: BaoClient): Promise { + 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 { + const res = await c.request<{ data: Partial & { 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 { + 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 { + await c.request('DELETE', `identity/entity/name/${enc(name)}`) +} + +export async function addAlias( + c: BaoClient, + a: { name: string; entityId: string; mountAccessor: string }, +): Promise { + 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 { + await c.request('DELETE', `identity/entity-alias/id/${enc(aliasId)}`) +} + +// ---- groups ---- + +export async function listGroups(c: BaoClient): Promise { + 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 { + const res = await c.request<{ data: Partial & { 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 { + 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 { + await c.request('DELETE', `identity/group/name/${enc(name)}`) +} diff --git a/src/features/identities/EntitiesTab.tsx b/src/features/identities/EntitiesTab.tsx new file mode 100644 index 0000000..dfc2e2a --- /dev/null +++ b/src/features/identities/EntitiesTab.tsx @@ -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(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 ( +
+ {entities.error &&

{entities.error.message}

} + + + + + + + + + + {entities.data?.map((e) => ( + + + + + + + ))} + +
EntityAliasesPolicies +
{e.name}{e.aliases.map((a) => a.name).join(', ') || '—'}{e.policies.join(', ') || '—'} + {' '} + +
+ {remove.error &&

{remove.error.message}

} + {!draft && ( + + )} + {draft && ( +
+ + setDraft({ ...draft, policies })} /> + {save.error &&

{save.error.message}

} +
+ {' '} + +
+ {draft.entity && ( +
+ Userpass aliases + {draft.entity.aliases.map((a) => ( +
+ {a.name}{' '} + +
+ ))} + + + {(attach.error || detach.error) &&

{(attach.error ?? detach.error)?.message}

} +
+ )} + + )} +
+ ) +} diff --git a/src/features/identities/GroupsTab.tsx b/src/features/identities/GroupsTab.tsx new file mode 100644 index 0000000..1ae1fab --- /dev/null +++ b/src/features/identities/GroupsTab.tsx @@ -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(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 ( +
+ {groups.error &&

{groups.error.message}

} + + + + + + + + + + {groups.data?.map((g) => ( + + + + + + + ))} + +
GroupMembersPolicies +
{g.name}{g.member_entity_ids.map(nameOf).join(', ') || '—'}{g.policies.join(', ') || '—'} + {' '} + +
+ {remove.error &&

{remove.error.message}

} + {!draft && ( + + )} + {draft && ( +
+ +
+ Member entities + {entities.data?.map((e) => ( + + ))} + {entities.data?.length === 0 &&

No entities yet.

} +
+ setDraft({ ...draft, policies })} /> + {save.error &&

{save.error.message}

} +
+ {' '} + +
+ + )} +
+ ) +} diff --git a/src/features/identities/IdentitiesPage.tsx b/src/features/identities/IdentitiesPage.tsx index 31b728f..4b8dc40 100644 --- a/src/features/identities/IdentitiesPage.tsx +++ b/src/features/identities/IdentitiesPage.tsx @@ -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

Identities

+ const [tab, setTab] = useState('Users') + return ( +
+

Identities

+ + {(client) => ( + <> +
+ {tabs.map((t) => ( + + ))} +
+ {tab === 'Users' && } + {tab === 'Entities' && } + {tab === 'Groups' && } + + )} +
+
+ ) } diff --git a/src/features/identities/UsersTab.test.tsx b/src/features/identities/UsersTab.test.tsx new file mode 100644 index 0000000..6c05d4f --- /dev/null +++ b/src/features/identities/UsersTab.test.tsx @@ -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( + + + , + ) + 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') +}) diff --git a/src/features/identities/UsersTab.tsx b/src/features/identities/UsersTab.tsx new file mode 100644 index 0000000..42cc52f --- /dev/null +++ b/src/features/identities/UsersTab.tsx @@ -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(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 ( +
+ {users.error &&

{users.error.message}

} + + + + + + + + + {users.data?.map((u) => ( + + + + + + ))} + +
UserPolicies +
{u.name}{u.policies.join(', ') || '—'} + {' '} + +
+ {remove.error &&

{remove.error.message}

} + {!draft && ( + + )} + {draft && ( +
+ + + + setDraft({ ...draft, policies })} /> + {save.error &&

{save.error.message}

} +
+ {' '} + +
+ + )} +
+ ) +} diff --git a/src/features/shared/PolicyPicker.tsx b/src/features/shared/PolicyPicker.tsx new file mode 100644 index 0000000..cc882bd --- /dev/null +++ b/src/features/shared/PolicyPicker.tsx @@ -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 ( +
+ Policies + {error &&

Could not load policies: {error.message}

} + {names.map((n) => ( + + ))} +
+ ) +} diff --git a/src/features/shared/RequireConnection.tsx b/src/features/shared/RequireConnection.tsx new file mode 100644 index 0000000..81914e0 --- /dev/null +++ b/src/features/shared/RequireConnection.tsx @@ -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 ( +

+ Not connected. Connect to OpenBao first. +

+ ) + } + return <>{children(client)} +} diff --git a/src/index.css b/src/index.css index a2283f4..2bf999a 100644 --- a/src/index.css +++ b/src/index.css @@ -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; +}