From c29b0cfd63366b744a21d3bfe299e0077055aa30 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Wed, 18 Nov 2026 10:41:27 +0000 Subject: [PATCH] Add New secret: create KV v2 secrets from the Secrets page Write-only values, create-only (cas: 0). Admin policy gains secret/data/* create; docs updated. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 6 +- docs/admin-guide.md | 2 +- docs/envbao-admin.hcl | 2 + docs/user-guide.md | 6 +- src/api/secrets.integration.test.ts | 10 +++ src/api/secrets.ts | 8 +++ src/features/secrets/NewSecretDialog.tsx | 85 +++++++++++++++++++++++ src/features/secrets/SecretsPage.test.tsx | 27 ++++++- src/features/secrets/SecretsPage.tsx | 25 ++++++- src/index.css | 13 ++++ src/model/mounts.test.ts | 7 +- src/model/mounts.ts | 11 +++ 12 files changed, 192 insertions(+), 10 deletions(-) create mode 100644 src/features/secrets/NewSecretDialog.tsx diff --git a/README.md b/README.md index 81311e3..41416c0 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Taken from the [demo stack](#quick-start-with-docker). - **Connect** with a token or a userpass login. Refuses sealed or uninitialised servers, and explains CORS and connection problems. - **Identities**: create, edit and delete userpass users, identity entities (with userpass aliases) and groups; create, list and revoke tokens. A new token's value is shown once. -- **Secrets**: browse KV v2 mounts and paths (names only; KV secret values are never read) and see which identities can reach a secret, through which policy, with which capabilities. +- **Secrets**: browse KV v2 mounts and paths and add new secrets (values are write-only: existing values are never read, shown or overwritten) and see which identities can reach a secret, through which policy, with which capabilities. - **Secrets engines**: create (KV v2, database, AWS, SSH), change the settings of, and delete secrets engine mounts, including KV v2 settings such as max versions. Deleting asks you to type the mount path, and says what will be lost and which policies still refer to it. - **Dynamic secrets**: for database (Postgres, ...), AWS and SSH engines, and a raw-JSON editor for any other engine type: create, edit and delete roles; configure the engine (database connections with rotate and reset, AWS root and lease, the SSH signing CA); generate credentials, sign SSH keys or issue OTPs; and browse, renew and revoke leases. Issued credentials are shown once and are never stored or cached by the UI. Passwords and private keys you type into config forms are write-only: they are never shown again. - **Access**: from an identity's **Access** button, grant it capabilities on a secret path (globs allowed) or access to a dynamic-engine role (generate credentials, manage the role), or revoke them, without writing policy HCL. A role's **Access** button shows who can already use it. @@ -161,6 +161,8 @@ path "sys/mounts/*" { capabilities = ["create", "read", "update", "delete # KV v2 settings (max versions, check-and-set) of the KV mount path "secret/config" { capabilities = ["read", "update"] } path "secret/metadata/*" { capabilities = ["list"] } +# Creating a new KV v2 secret. Create only: values can't be read back and existing secrets can't be overwritten +path "secret/data/*" { capabilities = ["create"] } # Dynamic secrets engines: roles, config, credentials and leases. The paths use the default mount # names (database/, aws/, ssh/); repeat a block with your own mount path for each engine you manage. @@ -209,7 +211,7 @@ Notes: - Creating **orphan** tokens (the "Orphan" checkbox) needs `sudo` on `auth/token/create`. It is deliberately not granted above; add `"sudo"` there if you want it. - The `sys/mounts/*` rule lets this account create, change and **delete any secrets engine**, which destroys its data and revokes its leases. Remove it (and the New / Settings / Delete buttons will report permission denied) if mounts are managed elsewhere. Mounting, tuning and deleting do not need `sudo`. - KV v2 settings (max versions, check-and-set) are stored by the engine at `/config`, so the policy only covers them on `secret/`. Creating another KV store with settings mounts it and then fails to save them; EnvBao tells you the store exists, and you can add `/config` to the policy and use **Settings**. -- If your KV v2 mount is not `secret/`, change `secret/metadata/*` and `secret/config`. The dynamic-engine rules name the default mounts (`database/`, `aws/`, `ssh/`), so change those too, or repeat a block for each mount. They deliberately avoid a `+/roles/*` wildcard, which would also match system paths such as `sys/config/cors`. +- If your KV v2 mount is not `secret/`, change `secret/metadata/*`, `secret/data/*` and `secret/config`. The dynamic-engine rules name the default mounts (`database/`, `aws/`, `ssh/`), so change those too, or repeat a block for each mount. They deliberately avoid a `+/roles/*` wildcard, which would also match system paths such as `sys/config/cors`. - Listing leases and revoking by prefix need `sudo` in OpenBao (looking up, renewing and revoking a single lease do not). Without it the Leases tab shows a permission error. - The `creds`, `sign` and `static-creds` lines let this account issue live database logins, AWS keys and SSH certificates. Remove them if the account should manage roles without being able to use them. - The account can create policies and attach them to identities, which is effectively the power to grant access to anything. Treat it as an administrator. diff --git a/docs/admin-guide.md b/docs/admin-guide.md index b4dec22..17af1c6 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -120,7 +120,7 @@ Required secrets: in `envbao-admin`, `PKGS_USER`, `PKGS_PASSWORD` and `DEPLOY_DI - **Token handling.** The token lives in memory only and is sent only to the OpenBao URL you entered. Anyone who can run script in the page (an XSS bug, a malicious browser extension) could use it, so keep the CSP and serve the UI from a dedicated origin. - **Credentials shown once.** Tokens and dynamic credentials appear when created and are never stored or cached by the UI. Password and private-key fields in configuration forms are write-only. -- **Secret values are never read.** The Secrets page lists names and metadata only. It cannot display KV secret values. +- **Secret values are write-only.** The Secrets page lists names and metadata only and cannot display KV secret values. **New secret** creates a secret (with `cas: 0`, so it can never overwrite one) and needs only `create` on `/data/*`. - **Audit.** The UI has no audit trail of its own. Turn on an OpenBao audit device; every UI action appears there under the signed-in account. - **Session length.** Sessions last as long as the token. Give the admin account a short TTL if you want people to sign in more often. - **Managed policies.** Grants are stored as policies named `envbao--` with an `# envbao-owner:` header. If someone edits one outside EnvBao, the UI treats it as read-only rather than overwrite it. Other policies are shown read-only. diff --git a/docs/envbao-admin.hcl b/docs/envbao-admin.hcl index ea7c85c..4f26394 100644 --- a/docs/envbao-admin.hcl +++ b/docs/envbao-admin.hcl @@ -33,6 +33,8 @@ path "sys/mounts/*" { capabilities = ["create", "read", "update", "delete # KV v2 settings (max versions, check-and-set) of the KV mount path "secret/config" { capabilities = ["read", "update"] } path "secret/metadata/*" { capabilities = ["list"] } +# Creating a new KV v2 secret. Create only: values can't be read back and existing secrets can't be overwritten +path "secret/data/*" { capabilities = ["create"] } # Dynamic secrets engines: roles, config, credentials and leases. The paths use the default mount # names (database/, aws/, ssh/); repeat a block with your own mount path for each engine you manage. diff --git a/docs/user-guide.md b/docs/user-guide.md index 1d45d78..e3a80ad 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -86,13 +86,13 @@ For each identity, EnvBao keeps one policy named `envbao--` (for exa **Secrets** is where you browse and manage secrets engines. At the top: - **New secrets engine** adds a mount (see [Managing secrets engines](#managing-secrets-engines)). -- The **Secrets engine** drop-down chooses which engine to work with, with **Settings** and **Delete** for that engine beside it. +- The **Secrets engine** drop-down chooses which engine to work with, with **Settings**, **Delete** and (for KV) **New secret** for that engine beside it. For a **KV** engine you browse folders and secrets with the breadcrumb under the toolbar. Select a secret to see **who can reach it**: every identity with access, through which policy, and with which capabilities. **Grant access** on that panel opens the grant form for the secret. ![Who can reach a secret](screenshots/secret-access.jpg) -EnvBao shows secret **names only**. It never reads or displays a secret's value. OpenBao applies the most specific matching policy path, and the table follows the same rule. It does not evaluate parameter constraints, control groups, MFA or templated paths (templated paths are approximated), so a policy using those may be over-reported and is flagged. +**New secret** (KV engines) adds a secret under the current folder: type a name such as `expo` and one or more key/value pairs. Values are write-only. EnvBao never reads or displays a secret's value, and it refuses to overwrite an existing secret. OpenBao applies the most specific matching policy path, and the table follows the same rule. It does not evaluate parameter constraints, control groups, MFA or templated paths (templated paths are approximated), so a policy using those may be over-reported and is flagged. ## Dynamic secrets engines @@ -162,7 +162,7 @@ If creating a KV engine succeeds but saving its KV settings fails, the page says ## Good to know - **Copy it now.** Tokens and generated credentials are shown once only. -- **Names, not values.** Secret values are never shown. +- **Write-only values.** Secret values can be created but are never shown, and existing secrets can't be changed here. - **Whole-instance reads.** The graph and Access panels read every user, entity, group, token and policy each time they load, which can be slow on very large instances. - **Not everything is managed here.** Auth methods other than userpass, nested groups and non-userpass aliases are not followed, and KV v1 mounts are not shown. See the README's limitations for the full list. - **Policies you did not create are read-only.** Change those with the OpenBao CLI. diff --git a/src/api/secrets.integration.test.ts b/src/api/secrets.integration.test.ts index 9763106..c8a5e02 100644 --- a/src/api/secrets.integration.test.ts +++ b/src/api/secrets.integration.test.ts @@ -71,3 +71,13 @@ describe('access model vs sys/capabilities-self', () => { } }) }) + +describe('writeSecret', () => { + test('creates a secret once and refuses to overwrite it', async () => { + const path = `it-${sfx}/new/expo` + await secrets.writeSecret(client, 'secret/', path, { TOKEN: 'v1' }) + await expect(secrets.writeSecret(client, 'secret/', path, { TOKEN: 'v2' })).rejects.toThrow() + const res = await client.request<{ data: { data: Record } }>('GET', `secret/data/${path}`) + expect(res.data.data).toEqual({ TOKEN: 'v1' }) + }) +}) diff --git a/src/api/secrets.ts b/src/api/secrets.ts index 598ea58..eada6ad 100644 --- a/src/api/secrets.ts +++ b/src/api/secrets.ts @@ -72,6 +72,14 @@ export async function listSecrets(c: BaoClient, mount: string, prefix: string): /** API path of a secret's data, which is what ACL policies are written against. */ export const dataPath = (mount: string, secret: string) => `${mount}data/${secret}` +/** + * Creates a new KV v2 secret. `cas: 0` makes OpenBao refuse if the secret already exists, so this can never + * overwrite a value (and only needs the `create` capability). + */ +export async function writeSecret(c: BaoClient, mount: string, path: string, data: Record): Promise { + await c.request('POST', dataPath(mount, enc(path)), { data, options: { cas: 0 } }) +} + export async function readPolicyHcl(c: BaoClient, name: string): Promise { try { const res = await c.request<{ data: { policy: string } }>('GET', `sys/policies/acl/${encodeURIComponent(name)}`) diff --git a/src/features/secrets/NewSecretDialog.tsx b/src/features/secrets/NewSecretDialog.tsx new file mode 100644 index 0000000..3f52e2b --- /dev/null +++ b/src/features/secrets/NewSecretDialog.tsx @@ -0,0 +1,85 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { useState } from 'react' +import type { BaoClient } from '../../api/bao' +import { writeSecret } from '../../api/secrets' +import { validateSecretPath } from '../../model/mounts' + +interface Row { + key: string + value: string +} + +/** Create a new KV v2 secret under the current path. Values are write-only and existing secrets are never overwritten. */ +export function NewSecretDialog({ client, mount, prefix, onClose, onDone }: { + client: BaoClient + mount: string + prefix: string + onClose: () => void + onDone: (path: string) => void +}) { + const qc = useQueryClient() + const [name, setName] = useState('') + const [rows, setRows] = useState([{ key: '', value: '' }]) + const [formError, setFormError] = useState(null) + + const create = useMutation({ + mutationFn: async () => { + const path = prefix + name.trim() + const data: Record = {} + for (const r of rows) data[r.key.trim()] = r.value + await writeSecret(client, mount, path, data) + await qc.invalidateQueries({ queryKey: ['kv-list'] }) + return path + }, + onSuccess: (path) => onDone(path), + }) + + const setRow = (i: number, patch: Partial) => setRows(rows.map((r, j) => (j === i ? { ...r, ...patch } : r))) + + function submit(e: React.FormEvent) { + e.preventDefault() + setFormError(null) + const nameError = validateSecretPath(name.trim()) + if (nameError) return setFormError(nameError) + const keys = rows.map((r) => r.key.trim()) + if (keys.some((k) => !k)) return setFormError('Every key needs a name.') + if (new Set(keys).size !== keys.length) return setFormError('Keys must be unique.') + create.mutate() + } + + return ( +
+
+ +
+ {rows.map((r, i) => ( +
+ setRow(i, { key: e.target.value })} /> + setRow(i, { value: e.target.value })} /> + +
+ ))} +
+ +
+
+

Values are write-only: they are never shown again, and an existing secret is never overwritten.

+ {(formError ?? create.error) &&

{formError ?? create.error?.message}

} + + +
+
+ ) +} diff --git a/src/features/secrets/SecretsPage.test.tsx b/src/features/secrets/SecretsPage.test.tsx index 49e207b..c5638c0 100644 --- a/src/features/secrets/SecretsPage.test.tsx +++ b/src/features/secrets/SecretsPage.test.tsx @@ -15,7 +15,7 @@ import { SecretsPage } from './SecretsPage' vi.mock('../../api/grants') vi.mock('../../api/identities') -vi.mock('../../api/secrets', async (orig) => ({ ...(await orig()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn() })) +vi.mock('../../api/secrets', async (orig) => ({ ...(await orig()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn(), writeSecret: vi.fn() })) vi.mock('../../api/tokens') vi.mock('../../api/mounts', async (orig) => ({ ...(await orig()), createMount: vi.fn(), tuneMount: vi.fn(), readKvConfig: vi.fn(), deleteMount: vi.fn(), mountImpact: vi.fn() })) @@ -292,3 +292,28 @@ test('asks to connect first', () => { ) expect(screen.getByText(/Not connected/)).toBeInTheDocument() }) + +test('adds a new secret under the current folder', async () => { + vi.mocked(api.writeSecret).mockResolvedValue() + const user = userEvent.setup() + render( + + + + + + + + , + ) + 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: 'New secret' })) + await user.click(screen.getByRole('button', { name: 'Create' })) + expect(screen.getByRole('alert')).toHaveTextContent('Name is required.') + await user.type(screen.getByLabelText(/^Name/), 'expo') + await user.type(screen.getByLabelText('Key 1'), 'TOKEN') + await user.type(screen.getByLabelText('Value 1'), 's3cret') + await user.click(screen.getByRole('button', { name: 'Create' })) + expect(api.writeSecret).toHaveBeenCalledWith(client, 'secret/', 'app/expo', { TOKEN: 's3cret' }) +}) diff --git a/src/features/secrets/SecretsPage.tsx b/src/features/secrets/SecretsPage.tsx index f7312e8..0fb8811 100644 --- a/src/features/secrets/SecretsPage.tsx +++ b/src/features/secrets/SecretsPage.tsx @@ -9,6 +9,7 @@ import { AccessPanel } from './AccessPanel' import { DeleteMountDialog } from './DeleteMountDialog' import { EngineView } from './EngineView' import { MountDialog } from './MountDialog' +import { NewSecretDialog } from './NewSecretDialog' function Browser({ client }: { client: BaoClient }) { const mounts = useMounts(client) @@ -16,7 +17,7 @@ function Browser({ client }: { client: BaoClient }) { const [mountChoice, setMount] = useState(null) const [prefix, setPrefix] = useState('') const [selected, setSelected] = useState(null) - const [dialog, setDialog] = useState<'create' | 'edit' | 'delete' | null>(null) + const [dialog, setDialog] = useState<'create' | 'edit' | 'delete' | 'secret' | null>(null) const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0] ?? null const mount = current?.path ?? null @@ -58,7 +59,7 @@ function Browser({ client }: { client: BaoClient }) { go('') }} /> - ) : dialog && dialog !== 'delete' && ( + ) : dialog && dialog !== 'delete' && dialog !== 'secret' && ( )} + {isKv && ( + + )} {dialogs} + {dialog === 'secret' && isKv && ( + { + closeDialog() + const folder = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '' + setPrefix(folder) + setSelected(path) + }} + /> + )} ) diff --git a/src/index.css b/src/index.css index 1072966..32673fe 100644 --- a/src/index.css +++ b/src/index.css @@ -1573,3 +1573,16 @@ button.danger-solid:hover:not(:disabled) { border: 1px solid var(--line); border-radius: var(--radius); } + +/* New secret form: key/value rows. */ +.kv-rows { + display: grid; + gap: var(--s2); + margin: var(--s3) 0; +} + +.kv-row { + display: flex; + gap: var(--s2); + align-items: center; +} diff --git a/src/model/mounts.test.ts b/src/model/mounts.test.ts index a047f1c..2ad23c6 100644 --- a/src/model/mounts.test.ts +++ b/src/model/mounts.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'vitest' -import { policiesReferencing, validateMountPath } from './mounts' +import { policiesReferencing, validateMountPath, validateSecretPath } from './mounts' const existing = ['secret/', 'database/', 'team/kv/'] @@ -38,3 +38,8 @@ test('finds policies with rules under a mount, however the mount is written', () expect(policiesReferencing(policies, 'secret')).toEqual(['a-uses', 'b-uses']) expect(policiesReferencing(policies, 'nothing/')).toEqual([]) }) + +test('validateSecretPath accepts plain and nested names and rejects bad ones', () => { + for (const p of ['expo', 'shell/expo', 'a b']) expect(validateSecretPath(p), p).toBeNull() + for (const p of ['', ' x', '/x', 'x/', 'a//b', 'a/../b', '.']) expect(validateSecretPath(p), p).not.toBeNull() +}) diff --git a/src/model/mounts.ts b/src/model/mounts.ts index 84b4739..19e8c31 100644 --- a/src/model/mounts.ts +++ b/src/model/mounts.ts @@ -42,3 +42,14 @@ export function policiesReferencing(policies: PolicyText[], mount: string): stri .map((p) => p.name) .sort((a, b) => a.localeCompare(b)) } + +/** Error message for a secret name/path (relative to a KV mount) that can't be used, or null. */ +export function validateSecretPath(path: string): string | null { + if (!path.trim()) return 'Name is required.' + if (path !== path.trim()) return 'Name must not start or end with spaces.' + if (path.startsWith('/') || path.endsWith('/')) return 'Name must not start or end with "/".' + const parts = path.split('/') + if (parts.some((p) => !p)) return 'Name must not contain empty parts ("//").' + if (parts.some((p) => p === '.' || p === '..')) return 'Name must not contain "." or ".." parts.' + return null +}