Secrets: grant access from the secret's detail card (ENB-20)
Adds a Grant access button to the selected secret. An inline form picks an identity (user, entity or group), whether to grant just this secret or its whole folder, and capabilities; the access table refreshes afterwards. - Extract CapabilityPicker and useRefreshAccess from the Access editor so both grant forms share them. - Stop Enter on the identity and engine dropdowns from submitting the form, which could grant access by accident. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
61bb6d912a
commit
791cf9603a
8 files changed
+287
-26
No files matched your search
@@ -1,9 +1,11 @@
|
||||
import { useState } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { dataPath } from '../../api/secrets'
|
||||
import { accessForPath } from '../../model/graph'
|
||||
import { pathMatches } from '../../model/policy'
|
||||
import { CapabilityChips } from '../shared/CapabilityChips'
|
||||
import { useAccessInputs } from '../shared/useAccessInputs'
|
||||
import { GrantHere } from './GrantHere'
|
||||
|
||||
interface Props {
|
||||
client: BaoClient
|
||||
@@ -14,13 +16,47 @@ interface Props {
|
||||
export function AccessPanel({ client, mount, secret }: Props) {
|
||||
const data = useAccessInputs(client)
|
||||
const path = dataPath(mount, secret)
|
||||
const [granting, setGranting] = useState(false)
|
||||
const [granted, setGranted] = useState<string | null>(null)
|
||||
|
||||
return (
|
||||
<section aria-label="Access" className="secret-detail">
|
||||
<header>
|
||||
<h2>{secret}</h2>
|
||||
<code>{path}</code>
|
||||
<div>
|
||||
<h2>{secret}</h2>
|
||||
<code>{path}</code>
|
||||
</div>
|
||||
{!granting && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={!data.data}
|
||||
onClick={() => {
|
||||
setGranted(null)
|
||||
setGranting(true)
|
||||
}}
|
||||
>
|
||||
Grant access
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
{granted && (
|
||||
<p role="status" className="note-ok">
|
||||
{granted}
|
||||
</p>
|
||||
)}
|
||||
{granting && data.data && (
|
||||
<GrantHere
|
||||
client={client}
|
||||
mount={mount}
|
||||
secret={secret}
|
||||
identities={data.data.identities}
|
||||
onClose={() => setGranting(false)}
|
||||
onGranted={(message) => {
|
||||
setGranting(false)
|
||||
setGranted(message)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{data.isPending && <p className="hint">Loading access…</p>}
|
||||
{data.error && <p role="alert">Could not load access: {data.error.message}</p>}
|
||||
{data.data && <Entries data={data.data} path={path} />}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useState, type FormEvent, type KeyboardEvent } from 'react'
|
||||
import type { BaoClient } from '../../api/bao'
|
||||
import { grantAccess } from '../../api/grants'
|
||||
import type { Identity } from '../../model/graph'
|
||||
import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
|
||||
import { CapabilityPicker } from '../shared/CapabilityPicker'
|
||||
import { useRefreshAccess } from '../shared/useRefreshAccess'
|
||||
|
||||
interface Props {
|
||||
client: BaoClient
|
||||
mount: string
|
||||
/** Secret path within the mount, e.g. "app/database". */
|
||||
secret: string
|
||||
identities: Identity[]
|
||||
onClose: () => void
|
||||
onGranted: (message: string) => void
|
||||
}
|
||||
|
||||
// Enter on a dropdown confirms the choice in some browsers and submits the form in others; never grant by accident.
|
||||
const noEnterSubmit = (e: KeyboardEvent<HTMLSelectElement>) => e.key === 'Enter' && e.preventDefault()
|
||||
|
||||
const GROUPS = [
|
||||
{ kind: 'user', label: 'Users' },
|
||||
{ kind: 'entity', label: 'Entities' },
|
||||
{ kind: 'group', label: 'Groups' },
|
||||
] as const
|
||||
|
||||
/** Grant an identity access to the secret that is open, without leaving the Secrets page. */
|
||||
export function GrantHere({ client, mount, secret, identities, onClose, onGranted }: Props) {
|
||||
const refresh = useRefreshAccess()
|
||||
// Tokens can't hold a managed policy: their policies are fixed when they are created.
|
||||
const people = GROUPS.flatMap((g) => identities.filter((i) => i.kind === g.kind).sort((a, b) => a.name.localeCompare(b.name)))
|
||||
const [who, setWho] = useState(0)
|
||||
const [scope, setScope] = useState<'secret' | 'folder'>('secret')
|
||||
const [caps, setCaps] = useState<KvCapability[]>(['read'])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const folder = secret.slice(0, secret.lastIndexOf('/') + 1)
|
||||
const path = scope === 'secret' ? secret : `${folder}*`
|
||||
const target = people[who]
|
||||
|
||||
const grant = useMutation({
|
||||
mutationFn: () => grantAccess(client, { kind: target.kind as 'user' | 'entity' | 'group', name: target.name }, kvGrantRules(mount, path, caps)),
|
||||
onSuccess: async () => {
|
||||
await refresh()
|
||||
onGranted(`Granted ${caps.join(', ')} on ${mount}${path} to ${target.kind} “${target.name}”.`)
|
||||
},
|
||||
})
|
||||
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
const err = validateGrantPath(path) ?? (caps.length === 0 ? 'Select at least one capability.' : null)
|
||||
setError(err)
|
||||
if (!err) grant.mutate()
|
||||
}
|
||||
|
||||
if (people.length === 0) {
|
||||
return (
|
||||
<p className="hint">
|
||||
There are no users, entities or groups to grant access to yet.{' '}
|
||||
<button type="button" className="link" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} aria-label="Grant access to this secret" className="wide grant-here">
|
||||
<h3>Grant access</h3>
|
||||
<label>
|
||||
Who
|
||||
<select value={who} onChange={(e) => setWho(Number(e.target.value))} onKeyDown={noEnterSubmit}>
|
||||
{GROUPS.map((g) => {
|
||||
const items = people.filter((p) => p.kind === g.kind)
|
||||
return (
|
||||
items.length > 0 && (
|
||||
<optgroup key={g.kind} label={g.label}>
|
||||
{items.map((p) => (
|
||||
<option key={`${p.kind}:${p.name}`} value={people.indexOf(p)}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)
|
||||
)
|
||||
})}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset>
|
||||
<legend>Where</legend>
|
||||
<label className="check">
|
||||
<input type="radio" name="grant-scope" checked={scope === 'secret'} onChange={() => setScope('secret')} />
|
||||
<span>
|
||||
Just this secret <code>{mount + secret}</code>
|
||||
</span>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input type="radio" name="grant-scope" checked={scope === 'folder'} onChange={() => setScope('folder')} />
|
||||
<span>
|
||||
Everything in <code>{mount + folder}</code>
|
||||
<span className="hint"> including subfolders and secrets added later</span>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
<CapabilityPicker value={caps} onChange={setCaps} />
|
||||
{(error || grant.error) && <p role="alert">{error ?? grant.error?.message}</p>}
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={grant.isPending}>
|
||||
Grant
|
||||
</button>
|
||||
<button type="button" onClick={onClose}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
|
||||
import { BaoClient } from '../../api/bao'
|
||||
import * as grants from '../../api/grants'
|
||||
import * as ids from '../../api/identities'
|
||||
import * as api from '../../api/secrets'
|
||||
import { SessionProvider } from '../../api/session'
|
||||
@@ -11,6 +12,7 @@ import { useSession } from '../../api/useSession'
|
||||
import * as tokens from '../../api/tokens'
|
||||
import { SecretsPage } from './SecretsPage'
|
||||
|
||||
vi.mock('../../api/grants')
|
||||
vi.mock('../../api/identities')
|
||||
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof api>()), listKvMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() }))
|
||||
vi.mock('../../api/tokens')
|
||||
@@ -72,6 +74,59 @@ test('navigates folders and shows who can reach a secret', async () => {
|
||||
expect(within(panel).getByText('secret/data/app/db')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
async function openSecret() {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<SessionProvider>
|
||||
<MemoryRouter>
|
||||
<Connected />
|
||||
<SecretsPage />
|
||||
</MemoryRouter>
|
||||
</SessionProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByRole('button', { name: 'go' }))
|
||||
await user.click(await screen.findByRole('button', { name: /app\// }))
|
||||
await user.click(await screen.findByRole('button', { name: /db/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
|
||||
return user
|
||||
}
|
||||
|
||||
test('grants an identity access to the open secret', async () => {
|
||||
vi.mocked(grants.grantAccess).mockResolvedValue()
|
||||
const user = await openSecret()
|
||||
await user.selectOptions(screen.getByLabelText('Who'), 'bob')
|
||||
await user.click(screen.getByLabelText('update'))
|
||||
await user.click(screen.getByRole('button', { name: 'Grant' }))
|
||||
|
||||
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'bob' }, [
|
||||
{ path: 'secret/data/app/db', capabilities: ['read', 'update'] },
|
||||
{ path: 'secret/metadata/app/db', capabilities: [] },
|
||||
])
|
||||
expect(await screen.findByRole('status')).toHaveTextContent('Granted read, update on secret/app/db to user “bob”.')
|
||||
expect(screen.queryByRole('form', { name: 'Grant access to this secret' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('can grant the whole folder instead of just the secret', async () => {
|
||||
vi.mocked(grants.grantAccess).mockResolvedValue()
|
||||
const user = await openSecret()
|
||||
await user.click(screen.getByLabelText(/Everything in/))
|
||||
await user.click(screen.getByRole('button', { name: 'Grant' }))
|
||||
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'alice' }, [
|
||||
{ path: 'secret/data/app/*', capabilities: ['read'] },
|
||||
{ path: 'secret/metadata/app/*', capabilities: [] },
|
||||
])
|
||||
})
|
||||
|
||||
test('shows why a grant failed and keeps the form open', async () => {
|
||||
vi.mocked(grants.grantAccess).mockRejectedValue(new Error('Policy "envbao-user-alice" was edited outside EnvBao'))
|
||||
const user = await openSecret()
|
||||
await user.click(screen.getByRole('button', { name: 'Grant' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('edited outside EnvBao')
|
||||
expect(screen.getByRole('form', { name: 'Grant access to this secret' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('asks to connect first', () => {
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
|
||||
@@ -79,7 +79,7 @@ function Browser({ client }: { client: BaoClient }) {
|
||||
)}
|
||||
</div>
|
||||
{selected ? (
|
||||
<AccessPanel client={client} mount={mount} secret={selected} />
|
||||
<AccessPanel key={`${mount}${selected}`} client={client} mount={mount} secret={selected} />
|
||||
) : (
|
||||
<p className="secret-placeholder">Select a secret to see who can reach it.</p>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user