From 791cf9603adfd3a659907082e243a5abffe66d1b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 20 Oct 2026 13:48:07 +0100 Subject: [PATCH] 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 --- src/features/access/AccessEditor.tsx | 29 ++---- src/features/secrets/AccessPanel.tsx | 40 +++++++- src/features/secrets/GrantHere.tsx | 119 ++++++++++++++++++++++ src/features/secrets/SecretsPage.test.tsx | 55 ++++++++++ src/features/secrets/SecretsPage.tsx | 2 +- src/features/shared/CapabilityPicker.tsx | 25 +++++ src/features/shared/useRefreshAccess.ts | 10 ++ src/index.css | 33 +++++- 8 files changed, 287 insertions(+), 26 deletions(-) create mode 100644 src/features/secrets/GrantHere.tsx create mode 100644 src/features/shared/CapabilityPicker.tsx create mode 100644 src/features/shared/useRefreshAccess.ts diff --git a/src/features/access/AccessEditor.tsx b/src/features/access/AccessEditor.tsx index 36f1c1c..3e3104e 100644 --- a/src/features/access/AccessEditor.tsx +++ b/src/features/access/AccessEditor.tsx @@ -1,11 +1,13 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { useState, type FormEvent } from 'react' import type { BaoClient } from '../../api/bao' import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants' import { listKvMounts, readPolicyHcl } from '../../api/secrets' -import { KV_CAPABILITIES, kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed' +import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed' import { groupGrants } from '../../model/grantRows' import { CapabilityChips } from '../shared/CapabilityChips' +import { CapabilityPicker } from '../shared/CapabilityPicker' +import { useRefreshAccess } from '../shared/useRefreshAccess' import { PathPicker } from './PathPicker' import { useConfirm } from '../shared/useConfirm' @@ -30,7 +32,6 @@ function PolicyView({ client, name }: { client: BaoClient; name: string }) { } export function AccessEditor({ client, target, onClose }: Props) { - const qc = useQueryClient() const confirm = useConfirm() const stateKey = ['grant-state', target.kind, target.name] const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) }) @@ -43,12 +44,7 @@ export function AccessEditor({ client, target, onClose }: Props) { const [formError, setFormError] = useState(null) const mount = mountChoice ?? mounts.data?.[0]?.path ?? '' - const done = () => - Promise.all( - [stateKey, ['users'], ['entities'], ['groups'], ['access-inputs'], ['policies']].map((queryKey) => - qc.invalidateQueries({ queryKey }), - ), - ) + const done = useRefreshAccess() const grant = useMutation({ mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)), @@ -163,6 +159,7 @@ export function AccessEditor({ client, target, onClose }: Props) { Secrets engine {mount && } -
- Capabilities - {KV_CAPABILITIES.map((c) => ( - - ))} -
+

Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.

diff --git a/src/features/secrets/AccessPanel.tsx b/src/features/secrets/AccessPanel.tsx index d92e8e0..f94b33a 100644 --- a/src/features/secrets/AccessPanel.tsx +++ b/src/features/secrets/AccessPanel.tsx @@ -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(null) return (
-

{secret}

- {path} +
+

{secret}

+ {path} +
+ {!granting && ( + + )}
+ {granted && ( +

+ {granted} +

+ )} + {granting && data.data && ( + setGranting(false)} + onGranted={(message) => { + setGranting(false) + setGranted(message) + }} + /> + )} {data.isPending &&

Loading access…

} {data.error &&

Could not load access: {data.error.message}

} {data.data && } diff --git a/src/features/secrets/GrantHere.tsx b/src/features/secrets/GrantHere.tsx new file mode 100644 index 0000000..7aaf568 --- /dev/null +++ b/src/features/secrets/GrantHere.tsx @@ -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) => 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(['read']) + const [error, setError] = useState(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 ( +

+ There are no users, entities or groups to grant access to yet.{' '} + +

+ ) + } + + return ( +
+

Grant access

+ +
+ Where + + +
+ + {(error || grant.error) &&

{error ?? grant.error?.message}

} +
+ + +
+ + ) +} diff --git a/src/features/secrets/SecretsPage.test.tsx b/src/features/secrets/SecretsPage.test.tsx index b6a86a4..d7d1bdf 100644 --- a/src/features/secrets/SecretsPage.test.tsx +++ b/src/features/secrets/SecretsPage.test.tsx @@ -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()), 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( + + + + + + + + , + ) + 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( diff --git a/src/features/secrets/SecretsPage.tsx b/src/features/secrets/SecretsPage.tsx index aa2cda2..2b2e698 100644 --- a/src/features/secrets/SecretsPage.tsx +++ b/src/features/secrets/SecretsPage.tsx @@ -79,7 +79,7 @@ function Browser({ client }: { client: BaoClient }) { )} {selected ? ( - + ) : (

Select a secret to see who can reach it.

)} diff --git a/src/features/shared/CapabilityPicker.tsx b/src/features/shared/CapabilityPicker.tsx new file mode 100644 index 0000000..93b633a --- /dev/null +++ b/src/features/shared/CapabilityPicker.tsx @@ -0,0 +1,25 @@ +import { KV_CAPABILITIES, type KvCapability } from '../../model/managed' + +interface Props { + value: KvCapability[] + onChange: (value: KvCapability[]) => void +} + +/** Checkboxes for the KV capabilities a grant can carry. */ +export function CapabilityPicker({ value, onChange }: Props) { + return ( +
+ Capabilities + {KV_CAPABILITIES.map((c) => ( + + ))} +
+ ) +} diff --git a/src/features/shared/useRefreshAccess.ts b/src/features/shared/useRefreshAccess.ts new file mode 100644 index 0000000..8c21f24 --- /dev/null +++ b/src/features/shared/useRefreshAccess.ts @@ -0,0 +1,10 @@ +import { useQueryClient } from '@tanstack/react-query' + +/** After a grant changes: reload everything that shows who can reach what. */ +export function useRefreshAccess() { + const qc = useQueryClient() + return () => + Promise.all( + ['grant-state', 'users', 'entities', 'groups', 'access-inputs', 'policies'].map((k) => qc.invalidateQueries({ queryKey: [k] })), + ) +} diff --git a/src/index.css b/src/index.css index 6499564..06d2103 100644 --- a/src/index.css +++ b/src/index.css @@ -1106,9 +1106,18 @@ button.link:hover:not(:disabled) { } .secret-detail header { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: var(--s2) var(--s4); + margin-bottom: var(--s4); +} + +.secret-detail header > div { display: grid; gap: var(--s1); - margin-bottom: var(--s4); + min-width: 0; } .secret-detail h2 { @@ -1422,3 +1431,25 @@ button.danger-solid:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); } + +/* Inline "Grant access" form inside the secret detail card. */ +.grant-here { + max-width: none; + margin: 0 0 var(--s4); + background: var(--bg); +} + +.caps { + grid-template-columns: repeat(auto-fill, minmax(6rem, 1fr)); +} + +.caps legend { + grid-column: 1 / -1; +} + +.note-ok { + padding: var(--s2) var(--s3); + background: var(--accent-soft); + border-radius: var(--radius); + color: var(--accent); +}