36 Commits
Author SHA1 Message Date
mattandClaude Sonnet 5.5 7b7071a318 Release v0.3.3
Release / check (push) Successful in 2m46s
CI / integration (push) Successful in 19s
Release / integration (push) Successful in 14s
CI / check (push) Successful in 3m12s
Release / image (push) Successful in 1m8s
Release / trigger-deploy (push) Successful in 3s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:30:30 +00:00
mattandClaude Sonnet 5.5 15e71e0e70 Dockerfile: run the Node build stage on the builder's platform
Cross-building under emulation failed on the arm64 runner; the stage only emits static files.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:30:30 +00:00
mattandClaude Sonnet 5.5 8c36460dea Release v0.3.2
CI / integration (push) Successful in 23s
CI / check (push) Successful in 24s
Release / integration (push) Successful in 17s
Release / check (push) Successful in 20s
Release / image (push) Failing after 28s
Release / trigger-deploy (push) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:26:56 +00:00
mattandClaude Sonnet 5.5 49f3d4b6a5 CI: build the release image for linux/amd64
The runner can be arm64; the deploy host is amd64 (v0.3.1 failed with exec format error).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:26:56 +00:00
mattandClaude Sonnet 5.5 42ea9d6531 Release v0.3.1
Release / integration (push) Successful in 23s
Release / check (push) Successful in 31s
CI / check (push) Successful in 32s
Release / image (push) Successful in 1m25s
Release / trigger-deploy (push) Successful in 2s
CI / integration (push) Successful in 3m10s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 14:20:37 +00:00
mattandClaude Sonnet 5.5 06366cd106 CI: audit production dependencies only
The dev-only picomatch advisory (via vite/vitest) has no non-breaking fix and
is not in the shipped image.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 14:20:37 +00:00
mattandClaude Sonnet 5.5 c6bb5b132a Release v0.3.0
Release / check (push) Failing after 11s
Release / integration (push) Successful in 20s
Release / image (push) Skipped
Release / trigger-deploy (push) Skipped
CI / integration (push) Successful in 22s
CI / check (push) Failing after 1m7s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 10:41:27 +00:00
mattandClaude Sonnet 5.5 c29b0cfd63 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 <noreply@anthropic.com>
2026-11-18 10:41:27 +00:00
mattandClaude Sonnet 5.5 d5f5faf2df Release v0.2.4
Release / integration (push) Successful in 20s
CI / integration (push) Successful in 21s
Release / check (push) Successful in 25s
Release / image (push) Successful in 16s
Release / trigger-deploy (push) Successful in 3s
CI / check (push) Successful in 3m6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 11:00:55 +00:00
mattandClaude Sonnet 5.5 4d0740dd97 Docs: user and administrator guides, screenshots; fix Generate and Leases layout
CI / integration (push) Successful in 1m25s
CI / check (push) Successful in 3m21s
Generate credentials no longer shows a raw JSON box for roles that take no input, and lease rows get proper button styling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 10:50:00 +00:00
mattandClaude Sonnet 5.5 3fa32b5076 Release v0.2.3
Release / integration (push) Successful in 18s
CI / check (push) Successful in 41s
Release / image (push) Successful in 21s
Release / trigger-deploy (push) Successful in 1s
CI / integration (push) Successful in 1m28s
Release / check (push) Successful in 21s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 22:03:59 +00:00
mattandClaude Sonnet 5.5 e646dade12 Tests: allow slower hooks in CI integration runs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 22:03:59 +00:00
mattandClaude Sonnet 5.5 eb99b7441b Release v0.2.2
CI / integration (push) Successful in 23s
Release / check (push) Successful in 28s
CI / check (push) Successful in 30s
Release / integration (push) Failing after 1m32s
Release / image (push) Skipped
Release / trigger-deploy (push) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 22:01:43 +00:00
mattandClaude Sonnet 5.5 88e3a4564b Tests: run integration files one at a time
They share one OpenBao and one Postgres; concurrent role creation failed in CI with 'tuple concurrently updated'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 22:01:43 +00:00
mattandClaude Sonnet 5.5 e13c850041 Release v0.2.1
CI / integration (push) Successful in 25s
Release / check (push) Successful in 31s
CI / check (push) Successful in 32s
Release / integration (push) Failing after 1m17s
Release / image (push) Skipped
Release / trigger-deploy (push) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 21:59:41 +00:00
mattandClaude Sonnet 5.5 156d9ddf78 Tests: don't search the database config for a password that equals the username
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 21:59:40 +00:00
mattandClaude Sonnet 5.5 4ce806e2d1 Release v0.2.0
CI / check (push) Successful in 53s
Release / check (push) Successful in 35s
Release / integration (push) Failing after 18s
Release / image (push) Skipped
Release / trigger-deploy (push) Skipped
CI / integration (push) Failing after 1m53s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:48:25 +00:00
mattandClaude Sonnet 5.5 d488bb42cc UI: signed-out menu and landing, form checkbox layout, Secrets header
The menu shows only Connect while signed out and the section links
once signed in; / goes to Connect or Identities accordingly. Yes/no
settings in the engine forms put the box beside its text. The Secrets
page now has New secrets engine on its own line, then a labelled engine
picker with Settings and Delete beside it, then the breadcrumbs, and
dynamic engines use the full width.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:47:31 +00:00
mattandClaude Sonnet 5.5 58b6230f9b Docs: admin policy and tests for managing secrets engine mounts
Adds sys/mounts/* and secret/config to the least-privilege policy and
runs create, tune and delete under only that policy. Mounting, tuning
and deleting need no sudo; KV settings are only covered on secret/, so
settings on another KV mount fail after the mount is created, which
the README and the UI's partial-create message now explain. Integration
tests also confirm that deleting a mount revokes the leases it issued
and that a blank TTL resets to the system default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:27:31 +00:00
mattandClaude Sonnet 5.5 1b3f6e4de5 Secrets: delete a secrets engine with a typed confirmation
The delete panel counts what will be lost (KV entries, or roles and
leases for dynamic engines), lists the policies that still grant access
under the mount, and keeps Delete disabled until the mount path is
typed. Anything it can't count is said so rather than hidden. Switching
mounts closes the panel, and the deleted mount's cached data is dropped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:25:21 +00:00
mattandClaude Sonnet 5.5 13a5353868 Secrets: create and change secrets engine mounts from the UI
New secrets engine (KV v2, database, aws, ssh) and per-mount Settings
dialogs on the Secrets page, including KV v2 settings. Settings
prefill from the explicit lease TTLs on the mount rather than the
effective ones, and the KV configuration is re-read on every open so a
stale copy is never written back. A server with no mounts can still
create its first one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:23:43 +00:00
mattandClaude Sonnet 5.5 66aa86028a Mounts: API, path validation and mountable engine types
Adds create/tune/delete for secrets engine mounts, the KV v2 settings
that live on the mount, and an impact summary for deletes. Mount lists
now carry description and explicit lease TTLs: sys/mounts/<path>/tune
reports the effective value, which would pin the system default if it
were saved back, so edits prefill from the list instead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:21:22 +00:00
mattandClaude Sonnet 5.5 fd20caa525 Config: show each database connection's URL and allowed roles
The connections table reads each connection and lists its URL and
allowed roles. Literal passwords in a URL are masked; templated
{{password}} URLs are shown as-is.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:09:42 +00:00
mattandClaude Sonnet 5.5 44e4eb75c9 Graph: highlight a selected node's links; nav: Connect only when signed out
Selecting a node highlights every edge into and out of it, with their
labels and the boxes at the far ends, and dims the rest. The Connect
menu item is shown only while signed out; when signed in, the name in
the menu links to the connection page so Disconnect stays reachable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:09:42 +00:00
mattandClaude Sonnet 5.5 11c9483a88 Demo and CI: Postgres and SSH server for the dynamic engines
docker compose now runs a Postgres with sample tables and an SSH server
that trusts the CA in OpenBao's ssh/ engine. seed.sh configures the
database engine (dynamic and static roles), the ssh CA and a role, a few
live leases, and grants for alice and the platform group. CI gains a
Postgres service so the database engine and its admin-policy rules are
tested against a real database (skipped when BAO_PG_URL is unset).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:58:59 +00:00
mattandClaude Sonnet 5.5 0eff098140 Docs: admin policy and README for dynamic engines
Adds database, aws, ssh and lease rules to the least-privilege policy,
with the ssh flows (config, roles, sign, OTP, lease list/lookup/revoke
and revoke-by-prefix) run under only that policy in the integration
tests. That showed listing leases and revoking by prefix need sudo.
README documents the new screens, enabling the engines, the AWS plugin
caveat and the credential handling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:53:37 +00:00
mattandClaude Sonnet 5.5 85a318c351 Access: grant and inspect access to dynamic engine roles
dynamicGrantRules expands a grant on a role into the credential paths
its requests need (generate) and the role CRUD paths (manage); unticked
access comes back empty so writing it revokes. Roles get an Access panel
showing who can generate credentials or manage them, and the identity
Access editor can pick dynamic mounts and roles. Checked against
capabilities-self and a real token in the integration tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:51:28 +00:00
mattandClaude Sonnet 5.5 48ee757e8d Secrets: browse, renew and revoke leases for dynamic engines
Adds a Leases tab that walks sys/leases/lookup under the mount, shows a
lease's timings on demand, renews renewable leases, and revokes one
lease or everything under a prefix after confirmation. Covered by unit
tests and an ssh OTP integration test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:45:14 +00:00
mattandClaude Sonnet 5.5 48746e2150 Secrets: engine config editors and one-time credential generation
Adds Config tab (database connections with rotate/reset, aws root and
lease, ssh CA with generate/import) and a Generate action on roles
(database/static creds, aws creds, ssh sign and OTP). Secret inputs are
write-only: never prefilled and omitted when blank so the stored value
is kept. Issued credentials live only in a gcTime-0 mutation and are
shown once, with revoke-now for leased credentials.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:30:08 +00:00
mattandClaude Sonnet 5.5 4fa7ff1497 Secrets: manage roles for database, aws, ssh and generic engines
Registry gains per-engine role kinds with field schemas (database
dynamic and static roles, aws, ssh); unknown engines get a raw JSON
role editor. RolesPanel lists, creates, edits and deletes roles, and
edits write back fields the form does not know about so they are not
dropped. Covered by unit tests and an ssh integration test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:24:50 +00:00
mattandClaude Sonnet 5.5 6daed8d388 Secrets: list all mounts and group dynamic engines by type
Adds listMounts and an engine registry (database, aws, ssh, generic
fallback). The Secrets page groups mounts by engine; KV v2 keeps the
path browser and dynamic mounts get a placeholder EngineView.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:20:40 +00:00
mattandClaude Sonnet 5.5 eba7c97de6 Release: dispatch the deploy after the image is pushed
CI / integration (push) Successful in 13s
CI / check (push) Successful in 17s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 13:13:00 +00:00
matt b1516f1eb0 Release v0.1.3
Release / integration (push) Successful in 20s
CI / integration (push) Successful in 21s
CI / check (push) Successful in 24s
Release / check (push) Successful in 2m12s
Release / image (push) Successful in 16s
2026-11-02 13:02:28 +00:00
mattandClaude Sonnet 5.5 a4dc871511 Release: push to the envbao ProGet Docker feed (ENB-26)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 13:02:27 +00:00
matt 1e65407227 Release v0.1.2
CI / integration (push) Successful in 17s
CI / check (push) Successful in 25s
Release / integration (push) Successful in 12s
Release / check (push) Successful in 16s
Release / image (push) Failing after 1m8s
2026-11-02 11:51:55 +00:00
mattandClaude Sonnet 5.5 51e2ad3d56 CI: drop fixed host port for OpenBao service, skip tag pushes in ci.yml (ENB-26)
CI / integration (push) Successful in 12s
CI / check (push) Successful in 17s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 11:51:22 +00:00
90 changed files with 5843 additions and 132 deletions

No files matched your search

+13 -3
View File
@@ -2,6 +2,7 @@ name: CI
on: on:
push: push:
branches: ["**"]
pull_request: pull_request:
jobs: jobs:
@@ -15,7 +16,7 @@ jobs:
cache: npm cache: npm
- run: npm ci - run: npm ci
- run: npm run lint - run: npm run lint
- run: npm audit --audit-level=high - run: npm audit --omit=dev --audit-level=high
- run: npm test - run: npm test
- run: npm run build - run: npm run build
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v3
@@ -31,12 +32,21 @@ jobs:
env: env:
BAO_DEV_ROOT_TOKEN_ID: root BAO_DEV_ROOT_TOKEN_ID: root
BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200 BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200
ports:
- 8200:8200
options: --cap-add=IPC_LOCK options: --cap-add=IPC_LOCK
# For the database secrets engine tests. Reached by service name from OpenBao, so no host port.
postgres:
image: postgres:17-alpine
env:
POSTGRES_DB: app
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd "pg_isready -U postgres -d app"
--health-interval 2s
--health-retries 15
env: env:
BAO_ADDR: http://openbao:8200 BAO_ADDR: http://openbao:8200
BAO_TOKEN: root BAO_TOKEN: root
BAO_PG_URL: postgresql://postgres:postgres@postgres:5432/app?sslmode=disable
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
+30 -5
View File
@@ -7,7 +7,7 @@ on:
env: env:
REGISTRY: pkgs.daubney.dev REGISTRY: pkgs.daubney.dev
IMAGE: pkgs.daubney.dev/${{ github.repository }} IMAGE: pkgs.daubney.dev/envbao/envbao-admin
jobs: jobs:
check: check:
@@ -20,7 +20,7 @@ jobs:
cache: npm cache: npm
- run: npm ci - run: npm ci
- run: npm run lint - run: npm run lint
- run: npm audit --audit-level=high - run: npm audit --omit=dev --audit-level=high
- run: npm test - run: npm test
- run: npm run build - run: npm run build
@@ -32,12 +32,21 @@ jobs:
env: env:
BAO_DEV_ROOT_TOKEN_ID: root BAO_DEV_ROOT_TOKEN_ID: root
BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200 BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200
ports:
- 8200:8200
options: --cap-add=IPC_LOCK options: --cap-add=IPC_LOCK
# For the database secrets engine tests. Reached by service name from OpenBao, so no host port.
postgres:
image: postgres:17-alpine
env:
POSTGRES_DB: app
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd "pg_isready -U postgres -d app"
--health-interval 2s
--health-retries 15
env: env:
BAO_ADDR: http://openbao:8200 BAO_ADDR: http://openbao:8200
BAO_TOKEN: root BAO_TOKEN: root
BAO_PG_URL: postgresql://postgres:postgres@postgres:5432/app?sslmode=disable
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
@@ -57,6 +66,22 @@ jobs:
- name: Build and push - name: Build and push
run: | run: |
VERSION="${GITHUB_REF_NAME#v}" VERSION="${GITHUB_REF_NAME#v}"
docker build -t "$IMAGE:$VERSION" -t "$IMAGE:latest" . # The runner may be arm64 (a Mac); the deploy host is amd64, so always build for it.
docker build --platform linux/amd64 -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
docker push "$IMAGE:$VERSION" docker push "$IMAGE:$VERSION"
docker push "$IMAGE:latest" docker push "$IMAGE:latest"
# Gitea cannot trigger another repo's workflow from a tag, so dispatch the deploy via the API.
trigger-deploy:
needs: [image]
if: ${{ !contains(github.ref_name, '-') }}
runs-on: ubuntu-latest
steps:
- name: Dispatch the deploy
env:
TAG: ${{ github.ref_name }}
TOKEN: ${{ secrets.DEPLOY_DISPATCH_TOKEN }}
run: |
curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "{\"ref\":\"main\",\"inputs\":{\"tag\":\"$TAG\"}}" \
"${{ gitea.server_url }}/api/v1/repos/matt/EnvBaoAdminDeploy/actions/workflows/deploy.yml/dispatches"
+3 -1
View File
@@ -1,4 +1,6 @@
FROM node:22-alpine AS build # The build stage only emits static files, so it runs on the builder's own architecture; only the nginx stage
# takes the target platform (linux/amd64, set in the release workflow). No emulation needed.
FROM --platform=$BUILDPLATFORM node:22-alpine AS build
WORKDIR /app WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci RUN npm ci
+101 -6
View File
@@ -6,12 +6,32 @@ Licensed under the [BSD 3-Clause License](LICENSE).
The UI talks directly to the OpenBao HTTP API from the browser. There is no backend. The UI talks directly to the OpenBao HTTP API from the browser. There is no backend.
## Documentation
- [User guide](docs/user-guide.md): signing in, identities, giving access, secrets and dynamic engines, the graph.
- [Administrator guide](docs/admin-guide.md): OpenBao setup, CORS, the admin policy, deployment and releases, security notes, troubleshooting.
## Screenshots
Taken from the [demo stack](#quick-start-with-docker).
| | |
| --- | --- |
| ![Who can reach a secret](docs/screenshots/secret-access.jpg) | ![Access graph, one identity highlighted](docs/screenshots/graph-highlight.jpg) |
| **Secrets**: who can reach a secret, and through which policy. | **Graph**: click a box to highlight every link from it. |
| ![Granting access](docs/screenshots/access-grants.jpg) | ![Database roles](docs/screenshots/engine-roles.jpg) |
| **Access**: grant or revoke without writing HCL. | **Dynamic secrets**: manage roles, generate credentials, browse leases. |
| ![Credentials shown once](docs/screenshots/generate-credentials.jpg) | ![Create a secrets engine](docs/screenshots/new-engine.jpg) |
| **Generate**: credentials are shown once and never stored. | **Secrets engines**: create, change and delete mounts. |
## What it does ## What it does
- **Connect** with a token or a userpass login. Refuses sealed or uninitialised servers, and explains CORS and connection problems. - **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. - **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; 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.
- **Access**: from an identity's **Access** button, grant it capabilities on a secret path (globs allowed) or revoke them, without writing policy HCL. - **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.
- **Graph**: Identity → Policy → Path graph, filterable by identity and path. Click a policy→path edge to revoke that grant. - **Graph**: Identity → Policy → Path graph, filterable by identity and path. Click a policy→path edge to revoke that grant.
## Using it ## Using it
@@ -33,6 +53,13 @@ Open http://localhost:8080 and connect to `http://localhost:8200` with token `ro
The stack also loads sample data from [`docker/seed.sh`](docker/seed.sh): five secrets under `secret/` (`app/`, `shared/`, `team-a/`), userpass users `alice`, `bob` and `carol` (password `password123`), entities for alice and bob, a `platform` group, a few grants, and a `ci-deploy` token. Edit the script to change it. If you already have the stack running, `docker compose down` first: the setup step only runs on a fresh start. The stack also loads sample data from [`docker/seed.sh`](docker/seed.sh): five secrets under `secret/` (`app/`, `shared/`, `team-a/`), userpass users `alice`, `bob` and `carol` (password `password123`), entities for alice and bob, a `platform` group, a few grants, and a `ci-deploy` token. Edit the script to change it. If you already have the stack running, `docker compose down` first: the setup step only runs on a fresh start.
It also runs two things for the dynamic secrets engines to manage:
- **Postgres** (database `app`, published on `127.0.0.1:5433`; sample `customers` and `orders` tables from [`docker/postgres/init.sql`](docker/postgres/init.sql)). The `database/` engine is wired to it with `readonly` and `readwrite` roles, an `app-static` role whose password OpenBao rotates, and a couple of live leases. Under **Secrets → database/**, click **Generate** on a role to get a working login, for example `psql -h 127.0.0.1 -p 5433 -U <username> app`.
- **An SSH server** (`127.0.0.1:2222`, users `deploy` and `alice`, with sample files). It accepts only certificates signed by the CA in OpenBao's `ssh/` engine. Under **Secrets → ssh/ → demo**, click **Generate**, paste a public key (`ssh-keygen -t ed25519 -f demo -N ''`, then `cat demo.pub`), save the signed key as `demo-cert.pub`, and run `ssh -i demo -o CertificateFile=demo-cert.pub -p 2222 deploy@127.0.0.1`.
The AWS engine is not part of the demo (it needs an AWS account).
To run just the UI image: `docker build -t envbao-admin . && docker run -p 8080:80 envbao-admin`. To run just the UI image: `docker build -t envbao-admin . && docker run -p 8080:80 envbao-admin`.
## OpenBao setup ## OpenBao setup
@@ -84,9 +111,19 @@ bao auth enable userpass
bao secrets enable -path=secret -version=2 kv # skip if already mounted bao secrets enable -path=secret -version=2 kv # skip if already mounted
``` ```
Dynamic engines are optional and appear under **Secrets** once mounted. You can mount them from the UI (**Secrets → New secrets engine**) or with the CLI:
```sh
bao secrets enable database
bao secrets enable ssh
bao secrets enable aws # see the note below
```
The AWS engine is not built into every OpenBao release (some ship it as an external plugin, and `bao secrets enable aws` fails with `plugin not found in the catalog`). Register the plugin first if yours needs it. The AWS screens follow the engine's documented API and are covered by unit tests only, not against a live AWS engine.
### Admin policy for the UI ### Admin policy for the UI
Least privilege for the account that uses the UI. The same policy is kept in [`docs/envbao-admin.hcl`](docs/envbao-admin.hcl), and the integration tests run every UI operation with only this policy, so it is known to be sufficient: Least privilege for the account that uses the UI. The same policy is kept in [`docs/envbao-admin.hcl`](docs/envbao-admin.hcl), and the integration tests run the UI operations with only this policy, so it is known to be sufficient for them. That covers identities, KV, the SSH engine and (when a Postgres is available) the database engine. The AWS rules follow the engine's documented paths but are not exercised against a live AWS engine:
```hcl ```hcl
# Least-privilege policy for the account that uses EnvBao Admin. # Least-privilege policy for the account that uses EnvBao Admin.
@@ -117,14 +154,66 @@ path "auth/token/revoke-accessor" { capabilities = ["update"] }
# Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser # Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser
path "sys/auth" { capabilities = ["read"] } path "sys/auth" { capabilities = ["read"] }
path "sys/mounts" { capabilities = ["read"] } path "sys/mounts" { capabilities = ["read"] }
# Secrets engine mounts: create, change (tune) and delete. Deleting a mount destroys everything in it
# and revokes its leases, so this is a powerful rule; leave it out if mounts are managed elsewhere.
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"] } 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.
# The creds/sign lines let this account issue live logins, keys and certificates; drop them to manage
# roles without being able to use them.
# database (postgres, ...)
path "database/roles" { capabilities = ["list"] }
path "database/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/static-roles" { capabilities = ["list"] }
path "database/static-roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/config" { capabilities = ["list"] }
path "database/config/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/rotate-root/*" { capabilities = ["update"] }
path "database/reset/*" { capabilities = ["update"] }
path "database/creds/*" { capabilities = ["read"] }
path "database/static-creds/*" { capabilities = ["read"] }
# aws
path "aws/roles" { capabilities = ["list"] }
path "aws/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "aws/config/root" { capabilities = ["create", "read", "update"] }
path "aws/config/lease" { capabilities = ["create", "read", "update"] }
path "aws/config/rotate-root" { capabilities = ["update"] }
path "aws/creds/*" { capabilities = ["read", "update"] }
# ssh
path "ssh/roles" { capabilities = ["list"] }
path "ssh/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "ssh/config/ca" { capabilities = ["create", "read", "update", "delete"] }
path "ssh/sign/*" { capabilities = ["update"] }
path "ssh/creds/*" { capabilities = ["update"] }
# Leases: browse, inspect, renew and revoke what the engines have issued
# (OpenBao requires sudo to list leases and to revoke by prefix)
path "sys/leases/lookup" { capabilities = ["update"] }
path "sys/leases/lookup/*" { capabilities = ["list", "sudo"] }
path "sys/leases/renew" { capabilities = ["update"] }
path "sys/leases/revoke" { capabilities = ["update"] }
path "sys/leases/revoke-prefix/*" { capabilities = ["update", "sudo"] }
``` ```
Notes: Notes:
- Listing token accessors needs `sudo` in OpenBao, so the Tokens tab needs it on `auth/token/accessors`. - Listing token accessors needs `sudo` in OpenBao, so the Tokens tab needs it on `auth/token/accessors`.
- 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. - 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.
- If your KV v2 mount is not `secret/`, change `secret/metadata/*`. - 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 `<mount>/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 `<mount>/config` to the policy and use **Settings**.
- 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. - 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.
### Admin login ### Admin login
@@ -192,15 +281,21 @@ BAO_ADDR=http://127.0.0.1:8200 BAO_TOKEN=root npm run test:integration # again
The integration tests need a dev server with userpass available (they enable it if missing) and a KV v2 mount at `secret/` (the dev-mode default). They create and delete their own uniquely named objects, but run them against a throwaway instance, not a real one. The integration tests need a dev server with userpass available (they enable it if missing) and a KV v2 mount at `secret/` (the dev-mode default). They create and delete their own uniquely named objects, but run them against a throwaway instance, not a real one.
The dynamic-engine and mount-management tests mount and unmount their own uniquely named engines (`ssh` and `kv` are built into OpenBao). The database tests are skipped unless `BAO_PG_URL` points at a Postgres whose user has `CREATEROLE`, as seen from OpenBao, for example `BAO_PG_URL='postgresql://postgres:secret@postgres:5432/app?sslmode=disable'`; CI starts one as a service, and `docker compose up -d postgres` gives you one on `127.0.0.1:5433`. The admin-policy tests use the default `ssh/` and `database/` mounts and skip those checks when the mount already exists, so they never overwrite a real CA or connection. The AWS engine tests skip when the server does not have it.
Some test files enable `userpass` at the same time, which can fail with `path is already in use at userpass/`. If that happens, add `-- --no-file-parallelism`.
CI runs on Gitea Actions (`.gitea/workflows/ci.yml`): lint, test and build, plus an integration job against an OpenBao dev container. CI runs on Gitea Actions (`.gitea/workflows/ci.yml`): lint, test and build, plus an integration job against an OpenBao dev container.
## Limitations ## Limitations
- **Browser-direct**: CORS must be enabled on OpenBao, and the token lives in the browser's memory (never written to storage). There is no server-side audit trail beyond OpenBao's own audit log. - **Browser-direct**: CORS must be enabled on OpenBao, and the token lives in the browser's memory (never written to storage). There is no server-side audit trail beyond OpenBao's own audit log.
- **Scope**: KV v2 only, and only userpass auth, tokens and identity entities/groups are managed. - **Scope**: KV v2 and the database, AWS and SSH dynamic engines (other engine types get a raw JSON role editor only, with no credential generation), and only userpass auth, tokens and identity entities/groups are managed. KV v1 is not shown.
- **Mount management**: a mount's path and type can't be changed, and there is no rename (OpenBao's remount revokes leases and would leave grants pointing at the old path). Only KV v2, database, AWS and SSH can be created; KV v1 is not upgraded. Deleting a mount leaves policies that mention it in place.
- **Credentials**: dynamic credentials appear once, in the browser, when generated; copy them then. Avoid generating them on a shared screen. Credentials without a lease (database static roles) cannot be revoked from the Leases tab.
- **Managed policies**: access is granted by writing one policy per user, entity or group, named `envbao-<kind>-<name>` (for example `envbao-user-alice`). If a managed policy is edited outside EnvBao (for example to add parameter constraints) it becomes read-only in the UI rather than being overwritten. All other policies are shown read-only. Policy names are lower-cased by OpenBao, so identities whose names differ only by case or punctuation would collide; EnvBao detects this and refuses to overwrite. - **Managed policies**: access is granted by writing one policy per user, entity or group, named `envbao-<kind>-<name>` (for example `envbao-user-alice`). If a managed policy is edited outside EnvBao (for example to add parameter constraints) it becomes read-only in the UI rather than being overwritten. All other policies are shown read-only. Policy names are lower-cased by OpenBao, so identities whose names differ only by case or punctuation would collide; EnvBao detects this and refuses to overwrite.
- **Tokens**: cannot be granted access after creation (OpenBao fixes a token's policies when it is created), so choose their policies when creating them. Tokens created by a token die with it unless created as orphans. - **Tokens**: cannot be granted access after creation (OpenBao fixes a token's policies when it is created), so choose their policies when creating them. Tokens created by a token die with it unless created as orphans.
- **Grants** write `<mount>/data/...` rules for read/create/update/delete and `<mount>/metadata/...` for list. `patch`, `sudo` and the KV `delete`/`undelete`/`destroy` sub-paths are not offered. - **Grants** write `<mount>/data/...` rules for read/create/update/delete and `<mount>/metadata/...` for list. `patch`, `sudo` and the KV `delete`/`undelete`/`destroy` sub-paths are not offered. For dynamic engines, *generate credentials* grants the credential paths of the role (`creds/<role>`, `static-creds/<role>`, or `sign/<role>` and `creds/<role>` for SSH) and *manage role* grants create/read/update/delete on `roles/<role>` plus list on `roles`. Engine-wide config and lease management are not grantable from the UI.
- **Access model**: follows OpenBao's "most specific path wins" rule. Parameter constraints, control groups, MFA and templated paths are not evaluated (templated paths are approximated), so the access views can over-report for policies that use them; such policies are flagged. - **Access model**: follows OpenBao's "most specific path wins" rule. Parameter constraints, control groups, MFA and templated paths are not evaluated (templated paths are approximated), so the access views can over-report for policies that use them; such policies are flagged.
- **Inheritance**: identity→policy edges and the Access panel show *effective* policies, including those a user inherits from an aliased entity and that entity's groups. Nested groups and non-userpass aliases are not followed. - **Inheritance**: identity→policy edges and the Access panel show *effective* policies, including those a user inherits from an aliased entity and that entity's groups. Nested groups and non-userpass aliases are not followed.
- **Scale**: the graph and Access panel read every user, entity, group, token and policy on each load, with no pagination, so large instances may be slow. - **Scale**: the graph and Access panel read every user, entity, group, token and policy on each load, with no pagination, so large instances may be slow.
+33 -2
View File
@@ -1,6 +1,8 @@
# Local demo: the UI plus a throwaway in-memory OpenBao dev server. # Local demo: the UI, a throwaway in-memory OpenBao dev server, and the things its dynamic secrets engines
# manage: a Postgres database and an SSH server that trusts OpenBao's SSH CA.
# docker compose up --build # docker compose up --build
# UI: http://localhost:8080 OpenBao: http://localhost:8200 token: root # UI: http://localhost:8080 OpenBao: http://localhost:8200 token: root
# Postgres: localhost:5433 (database "app") SSH: localhost:2222 (users "deploy" and "alice", certificates only)
services: services:
openbao: openbao:
image: openbao/openbao:latest image: openbao/openbao:latest
@@ -15,13 +17,30 @@ services:
interval: 2s interval: 2s
retries: 15 retries: 15
# Sample database for the "database" secrets engine. OpenBao connects as the "openbao" role (docker/postgres/init.sql).
postgres:
image: postgres:17-alpine
environment:
POSTGRES_DB: app
POSTGRES_PASSWORD: postgres-sample
volumes:
- ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
ports:
- "127.0.0.1:5433:5432"
healthcheck:
test: ["CMD", "pg_isready", "-U", "postgres", "-d", "app"]
interval: 2s
retries: 15
# One-shot: allow the UI origin to call OpenBao from the browser, then load sample # One-shot: allow the UI origin to call OpenBao from the browser, then load sample
# secrets, users, entities, a group and a token (see docker/seed.sh). # secrets, users, entities, a group, a token and the dynamic engines (see docker/seed.sh).
openbao-setup: openbao-setup:
image: openbao/openbao:latest image: openbao/openbao:latest
depends_on: depends_on:
openbao: openbao:
condition: service_healthy condition: service_healthy
postgres:
condition: service_healthy
environment: environment:
BAO_ADDR: http://openbao:8200 BAO_ADDR: http://openbao:8200
BAO_TOKEN: root BAO_TOKEN: root
@@ -30,6 +49,18 @@ services:
entrypoint: ["sh", "/seed.sh"] entrypoint: ["sh", "/seed.sh"]
restart: "no" restart: "no"
# Sample SSH server for the "ssh" secrets engine. It trusts the CA that seed.sh generates, so a certificate
# signed by OpenBao logs in; there are no passwords. See docker/sshd.
sshd:
build: ./docker/sshd
depends_on:
openbao-setup:
condition: service_completed_successfully
environment:
BAO_ADDR: http://openbao:8200
ports:
- "127.0.0.1:2222:22"
ui: ui:
build: . build: .
depends_on: depends_on:
+48
View File
@@ -0,0 +1,48 @@
-- Sample database for the docker-compose demo (runs once, on first start). Throwaway: all names and
-- passwords here are fake. OpenBao's database engine connects as "openbao" and creates, rotates and
-- drops logins for the dynamic and static roles that docker/seed.sh configures.
-- The account OpenBao itself uses. CREATEROLE lets it make and drop the short-lived logins.
CREATE ROLE openbao WITH LOGIN PASSWORD 'openbao-sample' CREATEROLE;
-- A fixed login for the static role: OpenBao rotates its password on a schedule instead of creating it.
CREATE ROLE app_static WITH LOGIN PASSWORD 'initial-not-a-real-password';
GRANT app_static TO openbao WITH ADMIN OPTION;
CREATE TABLE customers (
id serial PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id serial PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
total_cents integer NOT NULL,
status text NOT NULL DEFAULT 'new',
placed_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO customers (name, email) VALUES
('Ada Example', 'ada@example.test'),
('Grace Sample', 'grace@example.test'),
('Linus Placeholder', 'linus@example.test');
INSERT INTO orders (customer_id, total_cents, status) VALUES
(1, 4200, 'shipped'),
(1, 1999, 'new'),
(2, 12500, 'shipped'),
(3, 800, 'cancelled');
-- OpenBao hands these out to the logins it creates, so it must hold them WITH GRANT OPTION.
GRANT CONNECT ON DATABASE app TO openbao;
GRANT USAGE ON SCHEMA public TO openbao WITH GRANT OPTION;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO openbao WITH GRANT OPTION;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO openbao WITH GRANT OPTION;
-- What the static login may do.
GRANT CONNECT ON DATABASE app TO app_static;
GRANT USAGE ON SCHEMA public TO app_static;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO app_static;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_static;
+64
View File
@@ -37,6 +37,12 @@ path "secret/data/team-a/*" {
path "secret/metadata/team-a/*" { path "secret/metadata/team-a/*" {
capabilities = ["list"] capabilities = ["list"]
} }
path "database/creds/readonly" {
capabilities = ["read"]
}
path "ssh/sign/demo" {
capabilities = ["update"]
}
POLICY POLICY
bao policy write envbao-user-bob - >/dev/null <<'POLICY' bao policy write envbao-user-bob - >/dev/null <<'POLICY'
@@ -58,6 +64,9 @@ path "secret/data/app/*" {
path "secret/metadata/app/*" { path "secret/metadata/app/*" {
capabilities = ["list"] capabilities = ["list"]
} }
path "database/creds/*" {
capabilities = ["read"]
}
POLICY POLICY
# Hand-written, so EnvBao shows it read-only. # Hand-written, so EnvBao shows it read-only.
@@ -87,4 +96,59 @@ bao write identity/group name=platform member_entity_ids="$alice_id" policies=en
# --- A token --- # --- A token ---
bao token create -display-name=ci-deploy -policy=envbao-user-bob -ttl=24h >/dev/null bao token create -display-name=ci-deploy -policy=envbao-user-bob -ttl=24h >/dev/null
# --- Dynamic secrets: database (Postgres service "postgres", see docker/postgres/init.sql) ---
bao secrets enable database >/dev/null
bao write database/config/app \
plugin_name=postgresql-database-plugin \
allowed_roles="readonly,readwrite,app-static" \
connection_url="postgresql://{{username}}:{{password}}@postgres:5432/app?sslmode=disable" \
username=openbao password=openbao-sample >/dev/null
# Statements are JSON on stdin because they contain quotes and semicolons.
bao write database/roles/readonly - >/dev/null <<'JSON'
{
"db_name": "app",
"creation_statements": [
"CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';",
"GRANT SELECT ON ALL TABLES IN SCHEMA public TO \"{{name}}\";"
],
"default_ttl": "1h",
"max_ttl": "24h"
}
JSON
bao write database/roles/readwrite - >/dev/null <<'JSON'
{
"db_name": "app",
"creation_statements": [
"CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';",
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO \"{{name}}\";",
"GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO \"{{name}}\";"
],
"default_ttl": "1h",
"max_ttl": "8h"
}
JSON
# A fixed login whose password OpenBao rotates, rather than a new login per request.
bao write database/static-roles/app-static db_name=app username=app_static rotation_period=24h >/dev/null
# --- Dynamic secrets: SSH certificates (the "sshd" service trusts this CA) ---
bao secrets enable ssh >/dev/null
bao write ssh/config/ca generate_signing_key=true >/dev/null
bao write ssh/roles/demo - >/dev/null <<'JSON'
{
"key_type": "ca",
"allow_user_certificates": true,
"allowed_users": "deploy,alice",
"default_user": "deploy",
"default_extensions": { "permit-pty": "" },
"ttl": "30m",
"max_ttl": "4h"
}
JSON
# A couple of live leases so the Leases tab has something to show (credentials discarded).
bao read database/creds/readonly >/dev/null
bao read database/creds/readwrite >/dev/null
echo "Sample data loaded. Sign in as alice, bob or carol with password: password123" echo "Sample data loaded. Sign in as alice, bob or carol with password: password123"
echo "Dynamic engines: database/ (Postgres) and ssh/ (certificates for the sshd service, port 2222)."
+21
View File
@@ -0,0 +1,21 @@
# A tiny SSH server for the docker-compose demo. It trusts certificates signed by the CA in OpenBao's ssh/
# engine: the entrypoint fetches the CA public key from OpenBao at start-up. Throwaway; not hardened for real use.
FROM alpine:3.22
RUN apk add --no-cache openssh-server curl \
&& ssh-keygen -A \
&& for u in deploy alice; do \
adduser -D -s /bin/sh "$u" \
# sshd refuses locked accounts even for key logins, so give each a random password (password logins are off).
&& echo "$u:$(head -c 24 /dev/urandom | base64)" | chpasswd; \
done
COPY sshd_config /etc/ssh/sshd_config
COPY sample-data/deploy/ /home/deploy/
COPY sample-data/alice/ /home/alice/
RUN chown -R deploy:deploy /home/deploy && chown -R alice:alice /home/alice
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
EXPOSE 22
ENTRYPOINT ["/entrypoint.sh"]
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Wait for OpenBao's SSH CA (generated by docker/seed.sh), trust it, then run sshd in the foreground.
set -eu
CA_URL="${BAO_ADDR:-http://openbao:8200}/v1/ssh/public_key"
i=0
until curl -fsS "$CA_URL" -o /etc/ssh/trusted-user-ca-keys.pem 2>/dev/null && [ -s /etc/ssh/trusted-user-ca-keys.pem ]; do
i=$((i + 1))
[ "$i" -le 60 ] || { echo "No SSH CA at $CA_URL after 60 tries" >&2; exit 1; }
echo "Waiting for the SSH CA at $CA_URL ..."
sleep 2
done
echo "Trusting the CA from $CA_URL"
exec /usr/sbin/sshd -D -e
+3
View File
@@ -0,0 +1,3 @@
Alice's notes (sample data)
- rotate the staging database password
- ask platform about the new SSH role
@@ -0,0 +1,2 @@
You are logged in as "deploy" on the EnvBao demo SSH server, using a certificate signed by OpenBao.
Everything in this container is sample data.
@@ -0,0 +1,6 @@
# sample application config (fake values)
service: orders-api
environment: demo
database:
host: postgres
name: app
+12
View File
@@ -0,0 +1,12 @@
# Certificate logins only: no passwords, no root.
Port 22
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
AllowUsers deploy alice
# Written by entrypoint.sh from OpenBao's ssh/ engine.
TrustedUserCAKeys /etc/ssh/trusted-user-ca-keys.pem
LogLevel VERBOSE
+149
View File
@@ -0,0 +1,149 @@
# Administrator guide
This guide is for the person who installs EnvBao Admin and prepares OpenBao for it. If you want to *use* the UI, see the [user guide](user-guide.md). The README has the short version of everything here.
## How it fits together
EnvBao Admin is a static single-page app. There is no server component and no database: your browser loads the page and then talks **directly** to the OpenBao HTTP API, using a token you sign in with. That has three consequences:
- OpenBao must allow the UI's origin with **CORS**.
- Every action is performed with, and limited by, the signed-in account's OpenBao policies. The UI cannot do anything that account could not do with the CLI.
- The token is held in the page's memory only. Reloading the page signs you out, and nothing is written to browser storage.
```
browser ──(loads static files)──▶ nginx / any static host
│
└──(HTTP API, X-Vault-Token, CORS)──▶ OpenBao
```
## Prerequisites
- OpenBao 2.x, initialised and unsealed. (The UI refuses to connect to a sealed or uninitialised server and says so.)
- A KV v2 mount, normally `secret/`.
- The **userpass** auth method, if you want to manage users and sign in with a password.
- HTTPS for the UI and OpenBao in production. Browsers block an HTTPS page from calling an HTTP OpenBao.
## 1. Allow the UI's origin (CORS)
CORS is runtime configuration in OpenBao, not a listener setting:
```sh
bao write sys/config/cors \
enabled=true \
allowed_origins="https://envbao.example.com" \
allowed_headers="X-Vault-Token,Content-Type"
```
`allowed_origins` is a comma-separated list of exact origins (scheme, host and port). Writing `sys/config/cors` **replaces the whole list**, so include every origin each time. Once CORS is enabled, OpenBao rejects any request whose `Origin` is not listed, including OpenBao's own web UI at `/ui`; add OpenBao's own address if you still use it.
| Where the UI runs | Origin to allow |
| --- | --- |
| `npm run dev` | `http://localhost:5173` |
| Docker image / compose | `http://localhost:8080` |
| Production | your UI's origin, e.g. `https://envbao.example.com` |
| OpenBao's own web UI | OpenBao's address, e.g. `http://localhost:8200` |
## 2. Enable what the UI manages
```sh
bao auth enable userpass
bao secrets enable -path=secret -version=2 kv # skip if it already exists
```
Dynamic secrets engines are optional. Mount them with the CLI or from the UI (**Secrets → New secrets engine**):
```sh
bao secrets enable database
bao secrets enable ssh
bao secrets enable aws
```
Not every OpenBao build includes the AWS engine; if `bao secrets enable aws` reports `plugin not found in the catalog`, register the plugin first. The AWS screens follow the engine's documented API but have only been tested without a live AWS engine.
## 3. Create the administrator policy and login
The UI's account needs a policy. The least-privilege policy is [`envbao-admin.hcl`](envbao-admin.hcl) (it is also reproduced in the README), and the integration tests run every UI operation with only that policy.
```sh
bao policy write envbao-admin docs/envbao-admin.hcl
bao write auth/userpass/users/admin password='...' token_policies=envbao-admin
# or, for a token:
bao token create -policy=envbao-admin
```
Things to know about this policy:
- **It is an administrator.** The account can create policies and attach them to identities, which is effectively the power to grant access to anything. Protect it accordingly.
- **Mount rules are powerful.** `sys/mounts/*` lets the account create, tune and **delete** any secrets engine. Deleting a mount destroys everything in it and revokes its leases. Remove that block if mounts are managed somewhere else; the Secrets page then shows permission errors on New, Settings and Delete.
- **The `creds`, `sign` and `static-creds` lines let the account issue live logins, keys and certificates.** Delete them if the account should manage roles without being able to use them.
- **Mount names.** The policy uses the default mount names (`secret/`, `database/`, `ssh/`, `aws/`). If yours differ, repeat the relevant block with your mount path.
- **KV settings** (max versions, check-and-set) are changed through `<mount>/config`. The policy grants this for `secret/` only; add a rule for any other KV mount you want to configure.
- **Applying a new release does not update the policy.** The deploy ships the UI only. When a release adds features (v0.2.0 added mount management), re-apply `docs/envbao-admin.hcl` with `bao policy write` yourself.
### Delegating
You do not have to give everyone the full policy. Anything the signed-in account is denied simply shows OpenBao's permission error in the UI. A common split is a smaller policy for people who only manage roles and grants and never mounts or leases.
## 4. Deploy the UI
```sh
npm ci
npm run build
```
`dist/` is a static site. Serve it from any static host with a fallback to `index.html` for client-side routes, over HTTPS.
**Docker.** The release pipeline publishes `pkgs.daubney.dev/envbao/envbao-admin:<version>` and `:latest`. To build your own:
```sh
docker build -t envbao-admin .
docker run -p 8080:80 envbao-admin
```
**nginx / Caddy.** See the README for sample configs. The bundled [`nginx.conf`](../nginx.conf) also sets security headers, including a Content-Security-Policy whose `connect-src` allows any `http:`/`https:` origin, because the OpenBao address is typed on the Connect screen. If you only ever use one OpenBao, tighten `connect-src` to its address.
There is no build-time or runtime configuration; the OpenBao URL is entered at sign-in.
## 5. Releases and the deploy pipeline
Releases are driven by tags in the `envbao-admin` repository:
1. Bump the version (`package.json`, `package-lock.json`) in a "Release vX.Y.Z" commit and tag it `vX.Y.Z`.
2. Pushing the tag runs `.gitea/workflows/release.yml`: lint, audit, unit tests and build; integration tests against OpenBao and Postgres service containers; then the image build and push; then a dispatch to the `EnvBaoAdminDeploy` repository, which runs its Ansible playbook against the host (Docker Compose in `/opt/envbao-admin`).
3. Tags containing a `-` (pre-releases) build the image but do not deploy.
If a release did not deploy, open the run in the Gitea Actions tab: the integration job is the usual place for a release to stop, and a failure there skips the image and the deploy. The deploy can be run by hand from the deploy repository's Actions tab with the tag as input.
Required secrets: in `envbao-admin`, `PKGS_USER`, `PKGS_PASSWORD` and `DEPLOY_DISPATCH_TOKEN` (a token that may run workflows in the deploy repository); in `EnvBaoAdminDeploy`, `DEPLOY_SSH_KEY`, `DEPLOY_KNOWN_HOSTS`, `PKGS_USER`, `PKGS_PASSWORD` and optionally `NOTIFY_*`.
## Security notes
- **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 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 `<mount>/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-<kind>-<name>` 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.
## Troubleshooting
| Symptom | Cause and fix |
| --- | --- |
| "Cannot reach OpenBao" or a CORS message on Connect | The UI's origin is not in `sys/config/cors`, or the URL is wrong, or an HTTPS page is calling an HTTP OpenBao. |
| OpenBao's own `/ui` stopped working after enabling CORS | Add OpenBao's own address to `allowed_origins`. |
| "Server is sealed" / "not initialised" | Unseal or initialise OpenBao. |
| Permission denied on New / Settings / Delete (Secrets) | The account's policy lacks `sys/mounts/*`. Re-apply `envbao-admin.hcl`. |
| Permission denied on Leases | Listing leases and revoking by prefix need `sudo` on `sys/leases/lookup/*` and `sys/leases/revoke-prefix/*`. The shipped policy includes it. |
| Token list is empty or incomplete | Listing token accessors needs `sudo` in OpenBao; the shipped policy includes it. |
| A banner says the session has expired | The token expired, was revoked, or OpenBao sealed. Sign in again. |
| A policy is read-only in the UI | It is not an EnvBao-managed policy, or it was edited outside EnvBao. Edit it with the CLI. |
| Mount created but "saving KV settings failed" | The account may change `sys/mounts` but not `<mount>/config`. Add a `config` rule for that mount. |
| A new release is out but nothing changed | Check the release run and the deploy run in Gitea Actions; the UI can also be cached, so hard-reload. |
## Trying it out: the demo stack
```sh
docker compose up --build
```
Open http://localhost:8080 and connect to `http://localhost:8200` with token `root`. This starts a throwaway in-memory OpenBao dev server, a Postgres and an SSH server wired to the database and SSH engines, and the UI, loaded with sample data from `docker/seed.sh` (users `alice`, `bob` and `carol`, password `password123`). It is not for production. The screenshots in these guides were taken from it.
+48
View File
@@ -26,4 +26,52 @@ path "auth/token/revoke-accessor" { capabilities = ["update"] }
# Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser # Discovery: mounted auth methods and secrets engines, and KV v2 metadata for the secret browser
path "sys/auth" { capabilities = ["read"] } path "sys/auth" { capabilities = ["read"] }
path "sys/mounts" { capabilities = ["read"] } path "sys/mounts" { capabilities = ["read"] }
# Secrets engine mounts: create, change (tune) and delete. Deleting a mount destroys everything in it
# and revokes its leases, so this is a powerful rule; leave it out if mounts are managed elsewhere.
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"] } 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.
# The creds/sign lines let this account issue live logins, keys and certificates; drop them to manage
# roles without being able to use them.
# database (postgres, ...)
path "database/roles" { capabilities = ["list"] }
path "database/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/static-roles" { capabilities = ["list"] }
path "database/static-roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/config" { capabilities = ["list"] }
path "database/config/*" { capabilities = ["create", "read", "update", "delete"] }
path "database/rotate-root/*" { capabilities = ["update"] }
path "database/reset/*" { capabilities = ["update"] }
path "database/creds/*" { capabilities = ["read"] }
path "database/static-creds/*" { capabilities = ["read"] }
# aws
path "aws/roles" { capabilities = ["list"] }
path "aws/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "aws/config/root" { capabilities = ["create", "read", "update"] }
path "aws/config/lease" { capabilities = ["create", "read", "update"] }
path "aws/config/rotate-root" { capabilities = ["update"] }
path "aws/creds/*" { capabilities = ["read", "update"] }
# ssh
path "ssh/roles" { capabilities = ["list"] }
path "ssh/roles/*" { capabilities = ["create", "read", "update", "delete"] }
path "ssh/config/ca" { capabilities = ["create", "read", "update", "delete"] }
path "ssh/sign/*" { capabilities = ["update"] }
path "ssh/creds/*" { capabilities = ["update"] }
# Leases: browse, inspect, renew and revoke what the engines have issued
# (OpenBao requires sudo to list leases and to revoke by prefix)
path "sys/leases/lookup" { capabilities = ["update"] }
path "sys/leases/lookup/*" { capabilities = ["list", "sudo"] }
path "sys/leases/renew" { capabilities = ["update"] }
path "sys/leases/revoke" { capabilities = ["update"] }
path "sys/leases/revoke-prefix/*" { capabilities = ["update", "sudo"] }
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+168
View File
@@ -0,0 +1,168 @@
# User guide
EnvBao Admin lets you manage who can reach which secrets in OpenBao without writing policy HCL, and shows the result as a graph. This guide walks through the screens. If you are setting EnvBao up, see the [administrator guide](admin-guide.md).
The screenshots use the demo stack (`docker compose up`), whose sample data has users `alice`, `bob` and `carol`.
## Contents
- [Signing in](#signing-in)
- [Identities](#identities)
- [Giving someone access](#giving-someone-access)
- [Secrets](#secrets)
- [Dynamic secrets engines](#dynamic-secrets-engines)
- [Managing secrets engines](#managing-secrets-engines)
- [The access graph](#the-access-graph)
- [Good to know](#good-to-know)
## Signing in
Open the UI and choose **Connect**. Enter the OpenBao URL and either a **token**, or choose **Userpass** and enter a username and password. Until you are signed in, only the Connect page is available.
When you are connected, the Connect page becomes a status page with the server's version and seal state and your session: who you are, your policies, and when the token expires. **Disconnect** signs you out.
![Connection status](screenshots/connection.jpg)
Your session lasts as long as your token. When it expires, is revoked, or OpenBao is sealed, a banner links you back to sign in. Reloading the browser page also signs you out, because the token is only kept in memory.
What you can do depends on your OpenBao policy. If an action is not allowed for your account, OpenBao's "permission denied" message is shown.
## Identities
**Identities** has four tabs.
| Tab | What it is |
| --- | --- |
| **Users** | Userpass logins (username and password) and the policies attached to them. |
| **Entities** | OpenBao identity entities, with their userpass aliases. An entity ties one person's logins together. |
| **Groups** | Identity groups. Members inherit the group's policies. |
| **Tokens** | Standalone tokens. |
![Users](screenshots/identities.jpg)
Each row has **Access**, **Edit** and **Delete**. Use **New user** (or New entity, New group) under the table to create one. Policy chips in the table are green when EnvBao manages the policy and grey for policies it only displays.
### Tokens
The Tokens tab lists live tokens with their policies, expiry and accessor. **New token** creates one: set a display name, TTL, policies and whether it is renewable or orphaned. **The token's value is shown once**, right after creation. Copy it then; it cannot be shown again. **Revoke** ends a token immediately. Your own token is marked "(you)" and cannot be revoked here.
A token's policies are fixed when it is created, so you cannot grant access to an existing token afterwards. Choose its policies up front.
![Tokens](screenshots/tokens.jpg)
## Giving someone access
Click **Access** on a user, entity or group. The panel has two halves.
- **Granted by EnvBao** (left): what you have granted through this UI, with a **Revoke** button on each line, and a **Show policy HCL** link if you want to see the policy it writes. Below it, **Other policies** lists anything attached to the identity that was set up outside EnvBao. Those are shown read-only.
- **Grant access** (right): the form to add something.
![Access panel for alice](screenshots/access-grants.jpg)
### Granting access to a secret
1. Pick the **secrets engine** (a KV mount such as `secret/`).
2. Enter a **path within the mount**, for example `app/database`, or a glob such as `app/*` for everything under `app/`.
3. Tick the capabilities: read, create, update, delete, list.
4. Press **Grant**.
You enter the path as it appears inside the mount. EnvBao writes the underlying `data/` and `metadata/` policy paths for you. Granting a path that already has a grant replaces its capabilities.
### Granting access to a dynamic-engine role
Choose a database, AWS or SSH engine instead of KV, then pick a **role**, or tick *every role in the engine* to cover roles added later. Two permissions are offered:
- **Generate credentials**: the identity may request database logins, AWS keys, SSH certificates or one-time passwords from the role.
- **Manage role**: the identity may view, change and delete the role and list the engine's roles.
Unticking a permission and granting again removes it.
### How it is stored
For each identity, EnvBao keeps one policy named `envbao-<kind>-<name>` (for example `envbao-user-alice`). Edit such a policy outside EnvBao and the UI will show it read-only instead of overwriting your change.
## Secrets
**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**, **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)
**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
Database, AWS and SSH engines issue short-lived credentials on request instead of storing fixed secrets. Choosing one of these engines shows three tabs: **Roles**, **Config** and **Leases**. Any other engine type gets a raw JSON role editor only.
### Roles
A role describes what to hand out: for the database engine, the SQL that creates a login and its TTLs; for SSH, the certificate rules; for AWS, the policy or IAM settings. The database engine has **Dynamic roles** (a new login each time) and **Static roles** (one fixed login whose password OpenBao rotates).
![Roles](screenshots/engine-roles.jpg)
- **New role** creates one, and **Edit** changes it. TTLs accept values like `30m` or `1h`. Multi-statement SQL fields take statements separated by a blank line.
- **Access** shows who can already use the role, and lets you grant it.
- **Delete** removes the role. Credentials already issued from it stay valid until their leases end.
### Generate credentials
**Generate** asks OpenBao for credentials from the role: a database login, AWS keys, a signed SSH certificate (paste a public key first), or a one-time password. They appear **once**. Copy them straight away; they are not stored and cannot be shown again. **Revoke now** ends the lease immediately.
![Issued credentials](screenshots/generate-credentials.jpg)
### Config
Engine-level settings. For the database engine this is the list of **connections**: the connection URL (with `{{username}}` and `{{password}}` templates), and the roles each connection allows. You can add a connection, edit one, rotate its root credentials and reset it. For SSH it is the signing CA; for AWS the root credentials and lease settings. Password and private-key fields are **write-only**: leave one blank when editing to keep the stored value.
![Database connections](screenshots/engine-config.jpg)
### Leases
Every credential an engine issues has a lease. The tab lets you browse them by role, open **Details** (issued, expires, time remaining, last renewal), **Renew** one if it is renewable, **Revoke** one, or **Revoke all under this prefix** for everything beneath the folder you are in. Revoking makes the credentials stop working at once. Credentials with no lease, such as database static roles, cannot be revoked here.
![Leases](screenshots/leases.jpg)
## Managing secrets engines
### Create
**New secrets engine** opens a form. Choose a **type** (KV v2, database, AWS or SSH), a **path** (lower-case letters, digits, `-` and `_`, with optional `/` segments; it cannot overlap an existing mount or use a reserved name like `sys`), an optional description, and the type's settings: for KV, max versions, check-and-set and automatic version deletion; for the others, default and maximum lease TTLs. The new engine is selected when it has been created.
![New secrets engine](screenshots/new-engine.jpg)
If creating a KV engine succeeds but saving its KV settings fails, the page says so, and the engine remains mounted.
### Change
**Settings** edits the description and the settings above. The path and type cannot be changed, and there is no rename.
### Delete
**Delete** asks you to type the engine's path before it will proceed, and tells you what you would lose: the number of secrets, roles or leases, and the policies that still mention the engine. Deleting an engine permanently destroys everything in it and revokes all its leases. **It cannot be undone.** Policies that refer to a deleted engine are left in place.
![Deleting an engine](screenshots/delete-engine.jpg)
## The access graph
**Graph** draws identity → policy → path. Identities are on the left, policies in the middle and the paths they grant on the right, with capabilities on the lines. Bold policies are managed by EnvBao, and a dashed policy is attached to something but does not exist. Identities include the policies they inherit through entities and groups.
![Access graph](screenshots/graph.jpg)
- **Click a box** to highlight every line connected to it and fade the rest; the side panel shows its details.
- **Click a line** between a policy and a path to see the grant, and revoke it.
- Use the **Identity** and **Path** filters to narrow a busy graph, **Hide the default policy** to cut noise, and **Refresh** to reload.
- Zoom and pan with the controls or your mouse.
![Highlighting alice's links](screenshots/graph-highlight.jpg)
## Good to know
- **Copy it now.** Tokens and generated credentials are shown once only.
- **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.
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "envbao-admin", "name": "envbao-admin",
"version": "0.1.1", "version": "0.3.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "envbao-admin", "name": "envbao-admin",
"version": "0.1.1", "version": "0.3.3",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.104.5", "@tanstack/react-query": "^5.104.5",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "envbao-admin", "name": "envbao-admin",
"private": true, "private": true,
"version": "0.1.1", "version": "0.3.3",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"type": "module", "type": "module",
"scripts": { "scripts": {
+57
View File
@@ -0,0 +1,57 @@
import { render, screen } from '@testing-library/react'
import { useEffect, useRef, type ReactNode } from 'react'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { expect, test } from 'vitest'
import { BaoClient } from './api/bao'
import { SessionProvider } from './api/session'
import { useSession } from './api/useSession'
import { Home } from './Home'
import { Providers } from './test/providers'
/** Signs in first, and only renders its children once the session exists. */
function SignedIn({ children }: { children: ReactNode }) {
const { client, connect } = useSession()
// connect() isn't a stable function, so guard instead of listing it as a dependency (that would sign in forever).
const done = useRef(false)
useEffect(() => {
if (done.current) return
done.current = true
connect(new BaoClient('http://b', 't'), { accessor: 'a', display_name: 'alice', policies: [], ttl: 0, renewable: false })
})
return client ? children : null
}
function setup(landing: ReactNode) {
const router = createMemoryRouter(
[
{ path: '/', element: landing },
{ path: '/connect', element: <p>connect page</p> },
{ path: '/identities', element: <p>identities page</p> },
],
{ initialEntries: ['/'] },
)
render(
<Providers>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</Providers>,
)
return router
}
test('sends a signed-out visitor to the connect page', async () => {
const router = setup(<Home />)
expect(await screen.findByText('connect page')).toBeInTheDocument()
expect(router.state.location.pathname).toBe('/connect')
})
test('sends a signed-in visitor to identities', async () => {
const router = setup(
<SignedIn>
<Home />
</SignedIn>,
)
expect(await screen.findByText('identities page')).toBeInTheDocument()
expect(router.state.location.pathname).toBe('/identities')
})
+8
View File
@@ -0,0 +1,8 @@
import { Navigate } from 'react-router'
import { useSession } from './api/useSession'
/** The landing route: straight to the work when signed in, otherwise to the only page that can be used. */
export function Home() {
const { client } = useSession()
return <Navigate to={client ? '/identities' : '/connect'} replace />
}
+60
View File
@@ -0,0 +1,60 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { expect, test } from 'vitest'
import { BaoClient } from './api/bao'
import { SessionProvider } from './api/session'
import { useSession } from './api/useSession'
import { Layout } from './Layout'
import { Providers } from './test/providers'
function SignIn() {
const { connect } = useSession()
return (
<button type="button" onClick={() => connect(new BaoClient('http://b', 't'), { accessor: 'a', display_name: 'alice', policies: [], ttl: 0, renewable: false })}>
sign in
</button>
)
}
function setup() {
const router = createMemoryRouter([{ path: '/', element: <Layout />, children: [{ index: true, element: <SignIn /> }, { path: 'connect', element: <p>connect page</p> }] }])
render(
<Providers>
<SessionProvider>
<RouterProvider router={router} />
</SessionProvider>
</Providers>,
)
return userEvent.setup()
}
test('offers Connect only while signed out', async () => {
const user = setup()
const nav = screen.getByRole('navigation', { name: 'Main' })
expect(nav).toHaveTextContent('Connect')
expect(screen.getByRole('link', { name: 'Connect' })).toHaveAttribute('href', '/connect')
await user.click(screen.getByRole('button', { name: 'sign in' }))
expect(screen.queryByRole('link', { name: 'Connect' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Connection' })).not.toBeInTheDocument()
})
test('shows the section links only while signed in', async () => {
const user = setup()
const names = ['Identities', 'Secrets', 'Graph']
for (const n of names) expect(screen.queryByRole('link', { name: n })).not.toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Connect' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'sign in' }))
for (const n of names) expect(screen.getByRole('link', { name: n })).toBeInTheDocument()
})
test('while signed in, the signed-in name links to the connection details', async () => {
const user = setup()
await user.click(screen.getByRole('button', { name: 'sign in' }))
const me = screen.getByRole('link', { name: 'alice' })
expect(me).toHaveAttribute('href', '/connect')
await user.click(me)
expect(screen.getByText('connect page')).toBeInTheDocument()
})
+16 -8
View File
@@ -21,15 +21,23 @@ export function Layout() {
</a> </a>
<nav aria-label="Main"> <nav aria-label="Main">
<strong>EnvBao</strong> <strong>EnvBao</strong>
{links.map((l) => ( {/* Every page needs a connection, so signed out there is nothing to navigate to but Connect. */}
<NavLink key={l.to} to={l.to}> {client &&
{l.label} links.map((l) => (
<NavLink key={l.to} to={l.to}>
{l.label}
</NavLink>
))}
{client ? (
// Signed in: the name is the way back to the connection details and Disconnect.
<NavLink to="/connect" className="whoami" title="Connection details and sign out">
{tokenInfo?.display_name || 'token'}
</NavLink> </NavLink>
))} ) : (
{client && tokenInfo && <span className="whoami">{tokenInfo.display_name || 'token'}</span>} <NavLink to="/connect" className="connect">
<NavLink to="/connect" className="connect"> Connect
{client ? 'Connection' : 'Connect'} </NavLink>
</NavLink> )}
</nav> </nav>
{notice && ( {notice && (
<div role="alert" className="notice"> <div role="alert" className="notice">
+150
View File
@@ -6,6 +6,14 @@ import * as ids from './identities'
import * as secrets from './secrets' import * as secrets from './secrets'
import * as tokens from './tokens' import * as tokens from './tokens'
import { kvGrantRules } from '../model/managed' import { kvGrantRules } from '../model/managed'
import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from './engines/config'
import { generateCreds } from './engines/creds'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './engines/leases'
import { ENGINES } from './engines/registry'
import { pgTarget } from '../test/postgres'
import { createMount, deleteMount, mountImpact, PartialMountError, readKvConfig, tuneMount } from './mounts'
import { MOUNT_TYPES } from './engines/registry'
import { deleteRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './engines/roles'
// Everything the UI does, run with ONLY docs/envbao-admin.hcl (plus the default policy), so the // Everything the UI does, run with ONLY docs/envbao-admin.hcl (plus the default policy), so the
// documented least-privilege policy can't silently drift from what the app needs. // documented least-privilege policy can't silently drift from what the app needs.
@@ -98,3 +106,145 @@ describe('the documented admin policy is sufficient for every UI operation', ()
).rejects.toThrow(/sudo/) ).rejects.toThrow(/sudo/)
}) })
}) })
// docs/envbao-admin.hcl names the default mounts, so this needs the ssh engine at ssh/. It mounts one if the
// server has none (a dev server or CI), and skips rather than overwrite the CA of an ssh/ mount that was already there.
describe('the admin policy covers dynamic engines (ssh at the default mount)', () => {
let mounted = false
const ssh = ENGINES.ssh
const role = ssh.roleKinds[0]
const sshRole = `it-pol-${sfx}`
beforeAll(async () => {
const mounts = await root.request<{ data: Record<string, unknown> }>('GET', 'sys/mounts')
if (!('ssh/' in mounts.data)) {
await root.request('POST', 'sys/mounts/ssh', { type: 'ssh' })
mounted = true
}
})
afterAll(async () => {
if (mounted) await root.request('DELETE', 'sys/mounts/ssh').catch(() => {})
})
test('config, roles, credentials and leases', async (ctx) => {
if (!mounted) ctx.skip()
const ca = ssh.configs[0]
expect(await readConfig(admin, 'ssh/', ca)).toBeNull()
await runAction(admin, 'ssh/', ca.actions![0])
expect((await readConfig(admin, 'ssh/', ca))?.public_key).toBeTruthy()
await writeRole(admin, 'ssh/', role, sshRole, { key_type: 'ca', allow_user_certificates: true, allowed_users: '*', default_user: 'alice' })
expect(await listRoles(admin, 'ssh/', role)).toContain(sshRole)
expect((await readRole(admin, 'ssh/', role, sshRole)).key_type).toBe('ca')
const key = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDI/MhHH9Rd3dBZwAa4gQOkxfuw0ogMWlO2G4rlINbfv it'
expect((await generateCreds(admin, 'ssh/', role.creds[0], sshRole, { public_key: key })).data.signed_key).toBeTruthy()
await writeRole(admin, 'ssh/', role, `${sshRole}-otp`, { key_type: 'otp', default_user: 'alice', cidr_list: '10.0.0.0/8' })
const otp = await generateCreds(admin, 'ssh/', role.creds[1], `${sshRole}-otp`, { ip: '10.0.0.9' })
expect((await listLeases(admin, 'ssh/creds/')).length).toBeGreaterThan(0)
expect((await lookupLease(admin, otp.leaseId)).id).toBe(otp.leaseId)
// OTP leases can't be renewed, so this fails; what matters is that it fails for that reason and not for permissions
const renewError = await renewLease(admin, otp.leaseId).then(() => null, (e: Error) => e.message)
expect(renewError).not.toBeNull()
expect(renewError).not.toMatch(/permission denied/)
await revokeLease(admin, otp.leaseId)
const again = await generateCreds(admin, 'ssh/', role.creds[1], `${sshRole}-otp`, { ip: '10.0.0.10' })
expect(again.leaseId).toBeTruthy()
await revokePrefix(admin, `ssh/creds/${sshRole}-otp/`)
await deleteRole(admin, 'ssh/', role, sshRole)
await deleteRole(admin, 'ssh/', role, `${sshRole}-otp`)
await deleteConfig(admin, 'ssh/', ca)
})
})
// Same idea for the database engine at database/, when BAO_PG_URL points at a Postgres (see src/test/postgres.ts).
describe('the admin policy covers the database engine (at the default mount)', () => {
const pg = pgTarget()
const db = ENGINES.database
let mounted = false
beforeAll(async () => {
const mounts = await root.request<{ data: Record<string, unknown> }>('GET', 'sys/mounts')
if (pg && !('database/' in mounts.data)) {
await root.request('POST', 'sys/mounts/database', { type: 'database' })
mounted = true
}
})
afterAll(async () => {
if (mounted) await root.request('DELETE', 'sys/mounts/database').catch(() => {})
})
test('connection, roles, credentials and leases', async (ctx) => {
if (!mounted) ctx.skip()
const conn = db.configs[0]
const kind = db.roleKinds[0]
const cfg = emptyDraft(conn)
Object.assign(cfg.values, pg!.values)
await writeConfig(admin, 'database/', conn, payloadFromDraft(conn, cfg), 'app')
expect(await listConfigs(admin, 'database/', conn)).toEqual(['app'])
expect(await readConfig(admin, 'database/', conn, 'app')).not.toBeNull()
await runAction(admin, 'database/', conn.actions![1], 'app')
const role = emptyDraft(kind)
role.values.db_name = 'app'
role.values.creation_statements = pg!.creationStatements
await writeRole(admin, 'database/', kind, 'ro', payloadFromDraft(kind, role))
expect(await listRoles(admin, 'database/', kind)).toEqual(['ro'])
expect((await readRole(admin, 'database/', kind, 'ro')).db_name).toBe('app')
const creds = await generateCreds(admin, 'database/', kind.creds[0], 'ro', {})
expect((await listLeases(admin, 'database/creds/ro/')).length).toBe(1)
expect((await lookupLease(admin, creds.leaseId)).id).toBe(creds.leaseId)
await revokeLease(admin, creds.leaseId)
await generateCreds(admin, 'database/', kind.creds[0], 'ro', {})
await revokePrefix(admin, 'database/creds/ro/')
await deleteRole(admin, 'database/', kind, 'ro')
await deleteConfig(admin, 'database/', conn, 'app')
})
})
describe('the admin policy covers managing secrets engine mounts', () => {
const kv = MOUNT_TYPES.find((t) => t.type === 'kv')!
const sshType = MOUNT_TYPES.find((t) => t.type === 'ssh')!
const made: string[] = []
afterAll(async () => {
for (const p of made) await root.request('DELETE', `sys/mounts/${p}`).catch(() => {})
})
const find = async (path: string) => (await secrets.listMounts(admin)).find((m) => m.path === path)
test('create, tune, inspect and delete a dynamic engine', async () => {
const path = `it-pol-ssh-${sfx}`
made.push(path)
await createMount(admin, path, sshType, { description: 'hosts', default_lease_ttl: '1h' })
expect(await find(`${path}/`)).toMatchObject({ type: 'ssh', description: 'hosts', defaultLeaseTtl: 3600 })
await tuneMount(admin, path, sshType, { description: 'changed' })
expect(await find(`${path}/`)).toMatchObject({ description: 'changed', defaultLeaseTtl: 0 })
expect((await mountImpact(admin, `${path}/`, 'ssh')).kind).toBe('dynamic')
await deleteMount(admin, path)
expect(await find(`${path}/`)).toBeUndefined()
})
test('create and delete a KV v2 store without settings', async () => {
const path = `it-pol-kv-${sfx}`
made.push(path)
await createMount(admin, path, kv, { description: 'plain' })
expect(await find(`${path}/`)).toMatchObject({ type: 'kv', version: '2' })
await deleteMount(admin, path)
})
test('KV settings work on secret/ but not on other mounts, which the README says', async () => {
// secret/config is the one KV config path the policy names
const before = await readKvConfig(admin, 'secret/')
await tuneMount(admin, 'secret/', kv, { description: 'key/value secret storage', max_versions: String(before.max_versions), cas_required: before.cas_required === true })
const path = `it-pol-kvset-${sfx}`
made.push(path)
const err = await createMount(admin, path, kv, { max_versions: '3' }).catch((e: unknown) => e)
expect(err).toBeInstanceOf(PartialMountError)
expect((err as Error).message).toMatch(/was mounted, but saving its KV settings failed: .*permission denied/s)
expect(await find(`${path}/`)).toBeDefined()
})
})
+75
View File
@@ -0,0 +1,75 @@
import { expect, test, vi } from 'vitest'
import { BaoClient, BaoError } from '../bao'
import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from './config'
import { generateCreds } from './creds'
import { ENGINES } from './registry'
import { draftFromRole, emptyDraft, payloadFromDraft } from './roles'
const conn = ENGINES.database.configs[0]
const aws = ENGINES.aws.configs[0]
const awsCreds = ENGINES.aws.roleKinds[0].creds[0]
test('named configs are addressed by name and flatten connection_details', async () => {
const c = new BaoClient('http://b', 't')
const req = vi.spyOn(c, 'request').mockResolvedValue({
data: { plugin_name: 'postgresql-database-plugin', allowed_roles: ['ro'], connection_details: { connection_url: 'postgresql://x', username: 'bao' } },
})
vi.spyOn(c, 'list').mockResolvedValue(['b', 'a'])
expect(await listConfigs(c, 'database/', conn)).toEqual(['a', 'b'])
expect(await readConfig(c, 'database/', conn, 'my pg')).toMatchObject({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao' })
expect(req).toHaveBeenCalledWith('GET', 'database/config/my%20pg')
await writeConfig(c, 'database/', conn, { a: 1 }, 'pg')
expect(req).toHaveBeenCalledWith('POST', 'database/config/pg', { a: 1 })
await deleteConfig(c, 'database/', conn, 'pg')
expect(req).toHaveBeenCalledWith('DELETE', 'database/config/pg')
await runAction(c, 'database/', conn.actions![0], 'pg')
expect(req).toHaveBeenCalledWith('POST', 'database/rotate-root/pg', {})
})
test('single configs use the bare path and read as null when unconfigured', async () => {
const c = new BaoClient('http://b', 't')
const req = vi.spyOn(c, 'request').mockRejectedValue(new BaoError('not-found', 'nope', 404))
expect(await readConfig(c, 'aws/', aws)).toBeNull()
expect(req).toHaveBeenCalledWith('GET', 'aws/config/root')
req.mockRejectedValue(new BaoError('forbidden', 'denied', 403))
await expect(readConfig(c, 'aws/', aws)).rejects.toThrow('denied')
})
test('an engine that errors instead of 404ing reads as unconfigured only for its own message', async () => {
const c = new BaoClient('http://b', 't')
const ca = ENGINES.ssh.configs[0]
const req = vi.spyOn(c, 'request').mockRejectedValue(new BaoError('server', 'No default issuer currently configured', 400))
expect(await readConfig(c, 'ssh/', ca)).toBeNull()
req.mockRejectedValue(new BaoError('server', 'something else', 500))
await expect(readConfig(c, 'ssh/', ca)).rejects.toThrow('something else')
req.mockRejectedValue(new BaoError('server', 'No default issuer currently configured', 400))
await expect(readConfig(c, 'aws/', aws)).rejects.toThrow('No default issuer')
})
test('secret fields are never prefilled and are omitted when left blank', () => {
const draft = draftFromRole(conn, 'pg', { plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao', password: 'leaked' })
expect(draft.values.password).toBe('')
expect(payloadFromDraft(conn, draft)).not.toHaveProperty('password')
draft.values.password = 's3cret'
expect(payloadFromDraft(conn, draft)).toMatchObject({ password: 's3cret' })
expect(emptyDraft(conn).values.password).toBe('')
})
test('credential requests: POST sends inputs, result is normalised', async () => {
const c = new BaoClient('http://b', 't')
const req = vi.spyOn(c, 'request').mockResolvedValue({
lease_id: 'aws/creds/ci/abc',
lease_duration: 3600,
renewable: true,
data: { access_key: 'AK', secret_key: 'SK' },
warnings: null,
})
const creds = await generateCreds(c, 'aws/', awsCreds, 'ci', { ttl: '1h' })
expect(req).toHaveBeenCalledWith('POST', 'aws/creds/ci', { ttl: '1h' })
expect(creds).toEqual({ leaseId: 'aws/creds/ci/abc', leaseDuration: 3600, renewable: true, data: { access_key: 'AK', secret_key: 'SK' }, warnings: [] })
const dbCreds = ENGINES.database.roleKinds[0].creds[0]
await generateCreds(c, 'database/', dbCreds, 'ro', { ignored: true })
expect(req).toHaveBeenLastCalledWith('GET', 'database/creds/ro', undefined)
})
+42
View File
@@ -0,0 +1,42 @@
import { BaoError, type BaoClient } from '../bao'
import type { ActionDef, ConfigKind } from './registry'
import type { RoleData } from './roles'
const enc = encodeURIComponent
const where = (mount: string, kind: ConfigKind, name?: string) =>
kind.named ? `${mount}${kind.path}/${enc(name ?? '')}` : `${mount}${kind.path}`
/** Names of the configs of a named kind (database connections). */
export async function listConfigs(c: BaoClient, mount: string, kind: ConfigKind): Promise<string[]> {
return (await c.list(`${mount}${kind.path}`)).sort((a, b) => a.localeCompare(b))
}
/**
* Reads a config, flattening `kind.nested` into the top level. Returns null when nothing is configured yet.
* OpenBao never returns write-only values such as passwords, so none can appear here.
*/
export async function readConfig(c: BaoClient, mount: string, kind: ConfigKind, name?: string): Promise<RoleData | null> {
try {
const res = await c.request<{ data: RoleData } | undefined>('GET', where(mount, kind, name))
const data = res?.data
if (!data) return null
const nested = kind.nested ? data[kind.nested] : undefined
return nested && typeof nested === 'object' ? { ...data, ...(nested as RoleData) } : data
} catch (e) {
if (e instanceof BaoError && e.kind === 'not-found') return null
if (e instanceof BaoError && kind.unsetMessage && e.message.toLowerCase().includes(kind.unsetMessage)) return null
throw e
}
}
export async function writeConfig(c: BaoClient, mount: string, kind: ConfigKind, body: RoleData, name?: string): Promise<void> {
await c.request('POST', where(mount, kind, name), body)
}
export async function deleteConfig(c: BaoClient, mount: string, kind: ConfigKind, name?: string): Promise<void> {
await c.request('DELETE', where(mount, kind, name))
}
export async function runAction(c: BaoClient, mount: string, action: ActionDef, name?: string): Promise<void> {
await c.request('POST', `${mount}${action.path.replace('{name}', enc(name ?? ''))}`, action.body ?? {})
}
+34
View File
@@ -0,0 +1,34 @@
import type { BaoClient } from '../bao'
import type { CredKind } from './registry'
import type { RoleData } from './roles'
/** Credentials as issued. These are secrets: show them once and never put them in a query cache. */
export interface Credentials {
/** Empty for credentials without a lease (database static roles). */
leaseId: string
/** Seconds; 0 when the credentials have no expiry. */
leaseDuration: number
renewable: boolean
data: Record<string, unknown>
warnings: string[]
}
interface CredResponse {
lease_id?: string
lease_duration?: number
renewable?: boolean
data?: Record<string, unknown>
warnings?: string[] | null
}
export async function generateCreds(c: BaoClient, mount: string, kind: CredKind, role: string, body: RoleData): Promise<Credentials> {
const path = `${mount}${kind.path(role)}`
const res = await c.request<CredResponse>(kind.method, path, kind.method === 'POST' ? body : undefined)
return {
leaseId: res.lease_id ?? '',
leaseDuration: res.lease_duration ?? 0,
renewable: res.renewable ?? false,
data: res.data ?? {},
warnings: res.warnings ?? [],
}
}
@@ -0,0 +1,84 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { pgTarget } from '../../test/postgres'
import { BaoClient } from '../bao'
import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from './config'
import { generateCreds } from './creds'
import { listLeases, lookupLease, revokeLease } from './leases'
import { ENGINES } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
// Runs the UI's own form model against a real database engine and Postgres. Needs BAO_PG_URL (see src/test/postgres.ts).
const pg = pgTarget()
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const mount = `it-db-${sfx}/`
const conn = ENGINES.database.configs[0]
const kind = ENGINES.database.roleKinds[0]
describe.skipIf(!pg)('database engine against Postgres', () => {
beforeAll(async () => {
await client.request('POST', `sys/mounts/${mount.slice(0, -1)}`, { type: 'database' })
})
afterAll(async () => {
await client.request('DELETE', `sys/mounts/${mount.slice(0, -1)}`).catch(() => {})
})
test('creates a connection through the form model; the password is never read back', async () => {
const draft = emptyDraft(conn)
draft.name = 'app'
Object.assign(draft.values, pg!.values)
await writeConfig(client, mount, conn, payloadFromDraft(conn, draft), 'app')
expect(await listConfigs(client, mount, conn)).toEqual(['app'])
const read = await readConfig(client, mount, conn, 'app')
expect(read).toMatchObject({ plugin_name: 'postgresql-database-plugin', username: pg!.values.username })
expect(String(read!.connection_url)).toContain('{{username}}')
// Not a substring search: CI's password ("postgres") is also the username and the hostname.
expect(read).not.toHaveProperty('password')
expect(JSON.stringify(read)).not.toContain(`:${String(pg!.values.password)}@`)
// editing with the password left blank must keep the stored one, or the next credential request would fail
const edit = draftFromRole(conn, 'app', read!)
expect(edit.values.password).toBe('')
edit.values.allowed_roles = 'ro'
await writeConfig(client, mount, conn, payloadFromDraft(conn, edit), 'app')
expect((await readConfig(client, mount, conn, 'app'))!.allowed_roles).toEqual(['ro'])
await runAction(client, mount, conn.actions![1], 'app') // reset
})
test('creates a role with multi-statement SQL, generates credentials and revokes the lease', async () => {
const draft = emptyDraft(kind)
draft.name = 'ro'
draft.values.db_name = 'app'
draft.values.creation_statements = pg!.creationStatements
draft.values.default_ttl = '5m'
await writeRole(client, mount, kind, 'ro', payloadFromDraft(kind, draft))
expect(await listRoles(client, mount, kind)).toEqual(['ro'])
const back = draftFromRole(kind, 'ro', await readRole(client, mount, kind, 'ro'))
expect(back.values.default_ttl).toBe('300s')
expect(payloadFromDraft(kind, back).creation_statements).toHaveLength(2)
const creds = await generateCreds(client, mount, kind.creds[0], 'ro', {})
expect(String(creds.data.username)).toMatch(/^v-/)
expect(String(creds.data.password).length).toBeGreaterThan(8)
expect(creds.leaseId).toContain(`${mount}creds/ro/`)
expect((await lookupLease(client, creds.leaseId)).renewable).toBe(true)
expect((await listLeases(client, `${mount}creds/ro/`)).map((e) => e.path)).toContain(creds.leaseId)
await revokeLease(client, creds.leaseId)
expect(await listLeases(client, `${mount}creds/ro/`)).toEqual([])
})
test('a role whose SQL is wrong reports the database error', async () => {
const bad = emptyDraft(kind)
bad.values.db_name = 'app'
bad.values.creation_statements = 'CREATE NONSENSE "{{name}}";'
await writeRole(client, mount, kind, 'bad', payloadFromDraft(kind, bad))
await expect(generateCreds(client, mount, kind.creds[0], 'bad', {})).rejects.toThrow()
await deleteRole(client, mount, kind, 'bad')
await deleteRole(client, mount, kind, 'ro')
await deleteConfig(client, mount, conn, 'app')
expect(await listRoles(client, mount, kind)).toEqual([])
})
})
+50
View File
@@ -0,0 +1,50 @@
import { expect, test, vi } from 'vitest'
import { BaoClient } from '../bao'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases'
const c = () => new BaoClient('http://b', 't')
test('lists folders before lease ids, joining them onto the prefix', async () => {
const client = c()
const list = vi.spyOn(client, 'list').mockResolvedValue(['zz9', 'ro/', 'aa1'])
expect(await listLeases(client, 'database/creds/')).toEqual([
{ name: 'ro/', path: 'database/creds/ro/', isFolder: true },
{ name: 'aa1', path: 'database/creds/aa1', isFolder: false },
{ name: 'zz9', path: 'database/creds/zz9', isFolder: false },
])
expect(list).toHaveBeenCalledWith('sys/leases/lookup/database/creds/')
})
test('looks up a lease and maps its fields', async () => {
const client = c()
const req = vi.spyOn(client, 'request').mockResolvedValue({
data: { id: 'database/creds/ro/abc', issue_time: '2026-01-01T00:00:00Z', expire_time: null, last_renewal: null, renewable: true, ttl: 120 },
})
expect(await lookupLease(client, 'database/creds/ro/abc')).toEqual({
id: 'database/creds/ro/abc',
issueTime: '2026-01-01T00:00:00Z',
expireTime: null,
lastRenewal: null,
renewable: true,
ttl: 120,
})
expect(req).toHaveBeenCalledWith('PUT', 'sys/leases/lookup', { lease_id: 'database/creds/ro/abc' })
})
test('renew sends an increment only when given and returns the granted duration', async () => {
const client = c()
const req = vi.spyOn(client, 'request').mockResolvedValue({ lease_duration: 300 })
expect(await renewLease(client, 'a/b')).toBe(300)
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/renew', { lease_id: 'a/b' })
await renewLease(client, 'a/b', '1h')
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/renew', { lease_id: 'a/b', increment: '1h' })
})
test('revoke and revoke-prefix', async () => {
const client = c()
const req = vi.spyOn(client, 'request').mockResolvedValue(undefined)
await revokeLease(client, 'database/creds/ro/xyz')
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/revoke', { lease_id: 'database/creds/ro/xyz' })
await revokePrefix(client, 'database/creds/ro/')
expect(req).toHaveBeenLastCalledWith('PUT', 'sys/leases/revoke-prefix/database/creds/ro', {})
})
+59
View File
@@ -0,0 +1,59 @@
import type { BaoClient } from '../bao'
const enc = (path: string) => path.split('/').map(encodeURIComponent).join('/')
export interface LeaseEntry {
name: string
/** Full lease id, or for folders the prefix (trailing slash) to browse next. */
path: string
isFolder: boolean
}
export interface LeaseInfo {
id: string
/** ISO timestamps; expireTime is null for leases that never expire. */
issueTime: string
expireTime: string | null
lastRenewal: string | null
renewable: boolean
/** Seconds remaining. */
ttl: number
}
/**
* Lists leases under a prefix such as "database/creds/" (the mount plus a path). Folders end with "/" and the rest are
* lease ids. Needs sudo on sys/leases/lookup, which most tokens lack.
*/
export async function listLeases(c: BaoClient, prefix: string): Promise<LeaseEntry[]> {
const keys = await c.list(`sys/leases/lookup/${enc(prefix)}`)
return keys
.map((k) => ({ name: k, path: prefix + k, isFolder: k.endsWith('/') }))
.sort((a, b) => Number(b.isFolder) - Number(a.isFolder) || a.name.localeCompare(b.name))
}
export async function lookupLease(c: BaoClient, leaseId: string): Promise<LeaseInfo> {
const res = await c.request<{
data: { id: string; issue_time: string; expire_time: string | null; last_renewal: string | null; renewable: boolean; ttl: number }
}>('PUT', 'sys/leases/lookup', { lease_id: leaseId })
const d = res.data
return { id: d.id, issueTime: d.issue_time, expireTime: d.expire_time, lastRenewal: d.last_renewal, renewable: d.renewable, ttl: d.ttl }
}
/** Extends a lease by `increment` (e.g. "1h"); OpenBao may grant less. Returns the new lease duration in seconds. */
export async function renewLease(c: BaoClient, leaseId: string, increment?: string): Promise<number> {
const res = await c.request<{ lease_duration: number }>('PUT', 'sys/leases/renew', {
lease_id: leaseId,
...(increment ? { increment } : {}),
})
return res.lease_duration
}
/** Revokes one lease, which also deletes the credentials it issued (database user, AWS key, ...). */
export async function revokeLease(c: BaoClient, leaseId: string): Promise<void> {
await c.request('PUT', 'sys/leases/revoke', { lease_id: leaseId })
}
/** Revokes every lease under a prefix, e.g. all credentials issued from one role. Needs sudo. */
export async function revokePrefix(c: BaoClient, prefix: string): Promise<void> {
await c.request('PUT', `sys/leases/revoke-prefix/${enc(prefix.replace(/\/+$/, ''))}`, {})
}
+388
View File
@@ -0,0 +1,388 @@
import type { Capability } from '../../model/policy'
import type { Mount } from '../secrets'
import { isKvV2 } from '../secrets'
export type FieldType =
/** Single-line string. */
| 'text'
/** Multi-line string sent as-is (e.g. a JSON policy document). */
| 'textarea'
/** Duration such as "1h" or "3600s"; read back from OpenBao as seconds. */
| 'ttl'
/** Comma or newline separated values sent as a string array. */
| 'list'
/** Statements separated by blank lines (SQL can contain commas) sent as a string array. */
| 'statements'
| 'bool'
| 'select'
/** Write-only value (password, private key). Never prefilled; left blank it is omitted so the stored value is kept. */
| 'secret'
export interface FieldDef {
key: string
label: string
type: FieldType
required?: boolean
options?: string[]
help?: string
/** Render as a textarea (secret fields such as PEM keys). */
multiline?: boolean
}
/** How to ask OpenBao for credentials (or a signed certificate) for a role. */
export interface CredKind {
id: string
label: string
/** Path relative to the mount for a given role name. */
path: (role: string) => string
method: 'GET' | 'POST'
/** Request parameters; only sent for POST. */
inputs: FieldDef[]
/** ACL capabilities a token needs on `path` to make this request (and so what "generate" grants). */
capabilities: Capability[]
}
/** A one-off call on a config, e.g. rotating the root credentials. */
export interface ActionDef {
id: string
label: string
/** Path relative to the mount; "{name}" is replaced with the config name for named configs. */
path: string
body?: Record<string, unknown>
confirm: { title: string; message: string; confirmLabel: string }
}
/** Engine configuration: a named list (database connections) or a single endpoint (aws root, ssh CA). */
export interface ConfigKind {
id: string
label: string
/** Path relative to the mount; for named configs the name is appended. */
path: string
named: boolean
fields: FieldDef[]
/** Reads put these under a nested key (database: connection_details); merged into the form values. */
nested?: string
/** Read-only values to display after loading, e.g. the SSH CA public key. */
shown?: { key: string; label: string }[]
actions?: ActionDef[]
deletable?: boolean
/** Part of the error OpenBao returns when nothing is configured yet, for engines that don't answer 404. */
unsetMessage?: string
}
/** One family of roles under a mount, e.g. database "roles" and "static-roles". */
export interface RoleKind {
id: string
label: string
/** Path relative to the mount that roles are listed and written under. */
path: string
/** Empty means the role is edited as raw JSON (generic engines). */
fields: FieldDef[]
/** Ways to get credentials for a role of this kind. */
creds: CredKind[]
}
/** Describes a dynamic secrets engine the UI can manage. Grows in later phases (creds, config). */
export interface EngineDef {
/** Engine type as reported by sys/mounts. */
type: string
label: string
roleKinds: RoleKind[]
configs: ConfigKind[]
}
const DATABASE_ROLE: RoleKind = {
id: 'roles',
label: 'Dynamic roles',
path: 'roles',
fields: [
{ key: 'db_name', label: 'Database config name', type: 'text', required: true },
{
key: 'creation_statements',
label: 'Creation statements',
type: 'statements',
required: true,
help: 'Separate statements with a blank line. Use {{name}}, {{password}} and {{expiration}}.',
},
{ key: 'revocation_statements', label: 'Revocation statements', type: 'statements' },
{ key: 'renew_statements', label: 'Renew statements', type: 'statements' },
{ key: 'rollback_statements', label: 'Rollback statements', type: 'statements' },
{ key: 'default_ttl', label: 'Default TTL', type: 'ttl' },
{ key: 'max_ttl', label: 'Max TTL', type: 'ttl' },
],
creds: [{ id: 'creds', label: 'Generate credentials', path: (r) => `creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] }],
}
const DATABASE_STATIC_ROLE: RoleKind = {
id: 'static-roles',
label: 'Static roles',
path: 'static-roles',
fields: [
{ key: 'db_name', label: 'Database config name', type: 'text', required: true },
{ key: 'username', label: 'Database username', type: 'text', required: true },
{ key: 'rotation_statements', label: 'Rotation statements', type: 'statements' },
{ key: 'rotation_period', label: 'Rotation period', type: 'ttl' },
],
creds: [
{ id: 'static-creds', label: 'Read current credentials', path: (r) => `static-creds/${encodeURIComponent(r)}`, method: 'GET', inputs: [], capabilities: ['read'] },
],
}
const AWS_ROLE: RoleKind = {
id: 'roles',
label: 'Roles',
path: 'roles',
fields: [
{
key: 'credential_type',
label: 'Credential type',
type: 'select',
required: true,
options: ['iam_user', 'assumed_role', 'federation_token'],
},
{ key: 'role_arns', label: 'Role ARNs', type: 'list', help: 'For assumed_role.' },
{ key: 'policy_arns', label: 'Policy ARNs', type: 'list' },
{ key: 'policy_document', label: 'Policy document (JSON)', type: 'textarea' },
{ key: 'iam_groups', label: 'IAM groups', type: 'list', help: 'For iam_user.' },
{ key: 'default_sts_ttl', label: 'Default STS TTL', type: 'ttl' },
{ key: 'max_sts_ttl', label: 'Max STS TTL', type: 'ttl' },
{ key: 'permissions_boundary_arn', label: 'Permissions boundary ARN', type: 'text' },
{ key: 'user_path', label: 'IAM user path', type: 'text' },
],
creds: [
{
id: 'creds',
label: 'Generate credentials',
path: (r) => `creds/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['read', 'update'],
inputs: [
{ key: 'ttl', label: 'TTL', type: 'ttl', help: 'For STS credentials.' },
{ key: 'role_arn', label: 'Role ARN', type: 'text', help: 'Only when the role allows several.' },
],
},
],
}
const SSH_ROLE: RoleKind = {
id: 'roles',
label: 'Roles',
path: 'roles',
fields: [
{ key: 'key_type', label: 'Key type', type: 'select', required: true, options: ['ca', 'otp'] },
{ key: 'default_user', label: 'Default user', type: 'text' },
{ key: 'allowed_users', label: 'Allowed users', type: 'text', help: 'Comma separated; * allows any.' },
{ key: 'cidr_list', label: 'CIDR list', type: 'text', help: 'otp only. Comma separated.' },
{ key: 'ttl', label: 'TTL', type: 'ttl' },
{ key: 'max_ttl', label: 'Max TTL', type: 'ttl' },
{ key: 'allow_user_certificates', label: 'Allow user certificates', type: 'bool' },
{ key: 'allow_host_certificates', label: 'Allow host certificates', type: 'bool' },
{ key: 'allowed_extensions', label: 'Allowed extensions', type: 'text' },
],
creds: [
{
id: 'sign',
label: 'Sign a public key (CA)',
path: (r) => `sign/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['update'],
inputs: [
{ key: 'public_key', label: 'Public key', type: 'textarea', required: true },
{ key: 'valid_principals', label: 'Valid principals', type: 'text', help: 'Comma separated.' },
{ key: 'ttl', label: 'TTL', type: 'ttl' },
{ key: 'cert_type', label: 'Certificate type', type: 'select', options: ['user', 'host'] },
],
},
{
id: 'otp',
label: 'Generate an OTP',
path: (r) => `creds/${encodeURIComponent(r)}`,
method: 'POST',
capabilities: ['update'],
inputs: [
{ key: 'ip', label: 'Target IP', type: 'text', required: true },
{ key: 'username', label: 'Username', type: 'text' },
],
},
],
}
const DATABASE_CONNECTION: ConfigKind = {
id: 'connections',
label: 'Connections',
path: 'config',
named: true,
nested: 'connection_details',
deletable: true,
fields: [
{
key: 'plugin_name',
label: 'Plugin',
type: 'select',
required: true,
options: ['postgresql-database-plugin', 'mysql-database-plugin', 'mongodb-database-plugin', 'mssql-database-plugin'],
},
{
key: 'connection_url',
label: 'Connection URL',
type: 'text',
required: true,
help: 'e.g. postgresql://{{username}}:{{password}}@db:5432/app',
},
{ key: 'allowed_roles', label: 'Allowed roles', type: 'list', help: 'Role names, or * for any.' },
{ key: 'username', label: 'Admin username', type: 'text' },
{ key: 'password', label: 'Admin password', type: 'secret' },
{ key: 'verify_connection', label: 'Verify the connection when saving', type: 'bool' },
],
actions: [
{
id: 'rotate-root',
label: 'Rotate root credentials',
path: 'rotate-root/{name}',
confirm: {
title: 'Rotate the root credentials?',
message: 'OpenBao will change the admin password, and only OpenBao will know the new one.',
confirmLabel: 'Rotate',
},
},
{
id: 'reset',
label: 'Reset connection',
path: 'reset/{name}',
confirm: { title: 'Reset the connection?', message: 'The plugin connection is closed and reopened.', confirmLabel: 'Reset' },
},
],
}
const AWS_ROOT: ConfigKind = {
id: 'root',
label: 'Root credentials',
path: 'config/root',
named: false,
fields: [
{ key: 'access_key', label: 'Access key', type: 'text' },
{ key: 'secret_key', label: 'Secret key', type: 'secret' },
{ key: 'region', label: 'Region', type: 'text' },
{ key: 'iam_endpoint', label: 'IAM endpoint', type: 'text' },
{ key: 'sts_endpoint', label: 'STS endpoint', type: 'text' },
],
actions: [
{
id: 'rotate-root',
label: 'Rotate root credentials',
path: 'config/rotate-root',
confirm: {
title: 'Rotate the root access key?',
message: 'OpenBao will create a new access key and delete the old one.',
confirmLabel: 'Rotate',
},
},
],
}
const AWS_LEASE: ConfigKind = {
id: 'lease',
label: 'Lease',
path: 'config/lease',
named: false,
fields: [
{ key: 'lease', label: 'Default lease', type: 'ttl' },
{ key: 'lease_max', label: 'Max lease', type: 'ttl' },
],
}
const SSH_CA: ConfigKind = {
id: 'ca',
label: 'Signing CA',
path: 'config/ca',
named: false,
deletable: true,
unsetMessage: 'no default issuer',
fields: [
{ key: 'public_key', label: 'Public key', type: 'textarea', help: 'Import a key pair, or generate one below.' },
{ key: 'private_key', label: 'Private key', type: 'secret', multiline: true },
],
shown: [{ key: 'public_key', label: 'Current CA public key' }],
actions: [
{
id: 'generate',
label: 'Generate signing key',
path: 'config/ca',
body: { generate_signing_key: true },
confirm: {
title: 'Generate a new signing key?',
message: 'This replaces any existing CA, so certificates signed by the old key stop being trusted.',
confirmLabel: 'Generate',
},
},
],
}
export const ENGINES: Record<string, EngineDef> = {
database: { type: 'database', label: 'Database', roleKinds: [DATABASE_ROLE, DATABASE_STATIC_ROLE], configs: [DATABASE_CONNECTION] },
aws: { type: 'aws', label: 'AWS', roleKinds: [AWS_ROLE], configs: [AWS_ROOT, AWS_LEASE] },
ssh: { type: 'ssh', label: 'SSH', roleKinds: [SSH_ROLE], configs: [SSH_CA] },
}
/** Engine types that are managed as plain secret stores or by the system, not as dynamic engines. */
const NOT_DYNAMIC = new Set(['kv', 'generic', 'cubbyhole', 'system', 'identity'])
/** Known engine definition, or a generic fallback (raw JSON roles) for any other dynamic engine type. */
export function engineFor(type: string): EngineDef {
return (
ENGINES[type] ?? {
type,
label: type,
roleKinds: [{ id: 'roles', label: 'Roles', path: 'roles', fields: [], creds: [] }],
configs: [],
}
)
}
export type MountKind = 'kv' | 'dynamic'
/** KV v2 mounts use the path-tree browser; every other non-system engine is treated as dynamic. */
export function mountKind(m: Mount): MountKind | null {
if (isKvV2(m)) return 'kv'
if (NOT_DYNAMIC.has(m.type)) return null
return 'dynamic'
}
/** An engine type that can be mounted from the UI, with the settings its mount form offers. */
export interface MountType {
/** Engine type for sys/mounts. */
type: string
label: string
/** Mount options, e.g. KV version 2. */
options?: Record<string, string>
/** Settings kept on the mount itself (sys/mounts). */
fields: FieldDef[]
/** KV v2 settings kept by the engine at `<mount>config`, not by sys/mounts. */
configFields: FieldDef[]
}
const DESCRIPTION: FieldDef = { key: 'description', label: 'Description', type: 'text' }
const LEASE_TTLS: FieldDef[] = [
{ key: 'default_lease_ttl', label: 'Default lease TTL', type: 'ttl', help: 'Blank uses the system default.' },
{ key: 'max_lease_ttl', label: 'Max lease TTL', type: 'ttl', help: 'Blank uses the system default.' },
]
export const MOUNT_TYPES: MountType[] = [
{
type: 'kv',
label: 'KV v2',
options: { version: '2' },
fields: [DESCRIPTION],
configFields: [
{ key: 'max_versions', label: 'Max versions', type: 'text', help: 'Versions kept per secret. 0 keeps the system default.' },
{ key: 'cas_required', label: 'Require check-and-set on writes', type: 'bool' },
{ key: 'delete_version_after', label: 'Delete versions after', type: 'ttl', help: 'Blank never deletes them.' },
],
},
{ type: 'database', label: 'Database', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
{ type: 'aws', label: 'AWS', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
{ type: 'ssh', label: 'SSH', fields: [DESCRIPTION, ...LEASE_TTLS], configFields: [] },
]
/** The mount form for a mounted engine, or null for one the UI can't create (it can still delete it). */
export const mountTypeFor = (m: Pick<Mount, 'type'>): MountType | null => MOUNT_TYPES.find((t) => t.type === m.type) ?? null
+177
View File
@@ -0,0 +1,177 @@
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { BaoClient } from '../bao'
import { readConfig, runAction, writeConfig, deleteConfig } from './config'
import { generateCreds } from './creds'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from './leases'
import { accessForPath } from '../../model/graph'
import { dynamicGrantRules, renderManagedPolicy } from '../../model/managed'
import { pathMatches } from '../../model/policy'
import { capabilitiesSelf, listMounts } from '../secrets'
import { createToken, revokeToken } from '../tokens'
import { ENGINES } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const mount = `it-ssh-${sfx}/`
const kind = ENGINES.ssh.roleKinds[0]
const awsMount = `it-aws-${sfx}/`
// Not every OpenBao build bundles the AWS engine (some ship it as an external plugin).
let awsAvailable = false
// A throwaway public key made only for this test; there is no matching private key anywhere.
const PUBLIC_KEY = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDI/MhHH9Rd3dBZwAa4gQOkxfuw0ogMWlO2G4rlINbfv it'
beforeAll(async () => {
await client.request('POST', `sys/mounts/${mount.slice(0, -1)}`, { type: 'ssh' })
awsAvailable = await client
.request('POST', `sys/mounts/${awsMount.slice(0, -1)}`, { type: 'aws' })
.then(() => true)
.catch(() => false)
})
afterAll(async () => {
await client.request('DELETE', `sys/mounts/${mount.slice(0, -1)}`).catch(() => {})
await client.request('DELETE', `sys/mounts/${awsMount.slice(0, -1)}`).catch(() => {})
})
describe('dynamic engine roles (ssh)', () => {
test('the new mount is listed with its type', async () => {
const m = (await listMounts(client)).find((x) => x.path === mount)
expect(m?.type).toBe('ssh')
})
test('creates, lists, edits and deletes a role through the form model', async () => {
expect(await listRoles(client, mount, kind)).toEqual([])
const draft = emptyDraft(kind)
draft.values.key_type = 'ca'
draft.values.allowed_users = 'alice,bob'
draft.values.ttl = '30m'
draft.values.allow_user_certificates = true
await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, draft))
expect(await listRoles(client, mount, kind)).toEqual(['ops'])
const read = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops'))
expect(read.values).toMatchObject({ key_type: 'ca', allowed_users: 'alice,bob', ttl: '1800s', allow_user_certificates: true })
// an edit writes the whole role back, so values it did not touch must survive
read.values.max_ttl = '2h'
await writeRole(client, mount, kind, 'ops', payloadFromDraft(kind, read))
const again = draftFromRole(kind, 'ops', await readRole(client, mount, kind, 'ops'))
expect(again.values).toMatchObject({ allowed_users: 'alice,bob', ttl: '1800s', max_ttl: '7200s' })
await deleteRole(client, mount, kind, 'ops')
expect(await listRoles(client, mount, kind)).toEqual([])
})
})
describe('dynamic engine config and credentials', () => {
const ca = ENGINES.ssh.configs[0]
test('an unconfigured CA reads as null, then generate, sign and delete', async () => {
expect(await readConfig(client, mount, ca)).toBeNull()
await runAction(client, mount, ca.actions![0])
const cfg = await readConfig(client, mount, ca)
expect(cfg?.public_key).toMatch(/^ssh-rsa /)
const role = emptyDraft(kind)
role.values.allow_user_certificates = true
role.values.allowed_users = '*'
role.values.default_user = 'alice'
role.values.ttl = '10m'
await writeRole(client, mount, kind, 'signer', payloadFromDraft(kind, role))
const sign = kind.creds[0]
const out = await generateCreds(client, mount, sign, 'signer', { public_key: PUBLIC_KEY })
expect(String(out.data.signed_key)).toMatch(/^ssh-ed25519-cert-v01@openssh.com /)
await deleteConfig(client, mount, ca)
expect(await readConfig(client, mount, ca)).toBeNull()
})
test('OTP credentials come with a lease that can be revoked', async () => {
const role = emptyDraft(kind)
role.values.key_type = 'otp'
role.values.default_user = 'alice'
role.values.cidr_list = '10.0.0.0/8'
await writeRole(client, mount, kind, 'otp', payloadFromDraft(kind, role))
const out = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.3' })
expect(out.leaseId).toContain('/creds/otp/')
expect(out.data.key).toBeTruthy()
await revokeLease(client, out.leaseId)
})
test('leases can be browsed, inspected, renewed and revoked by prefix', async () => {
const a = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.3' })
const b = await generateCreds(client, mount, kind.creds[1], 'otp', { ip: '10.1.2.4' })
// folders first: mount -> creds/ -> otp/ -> lease ids
expect(await listLeases(client, mount)).toContainEqual({ name: 'creds/', path: `${mount}creds/`, isFolder: true })
const ids = (await listLeases(client, `${mount}creds/otp/`)).map((e) => e.path)
expect(ids).toEqual(expect.arrayContaining([a.leaseId, b.leaseId]))
const info = await lookupLease(client, a.leaseId)
expect(info.id).toBe(a.leaseId)
expect(info.ttl).toBeGreaterThan(0)
expect(info.renewable).toBe(false)
// OTP leases are not renewable, and the UI only offers Renew when renewable; OpenBao says so itself
await expect(renewLease(client, a.leaseId)).rejects.toThrow()
await revokePrefix(client, `${mount}creds/otp/`)
expect(await listLeases(client, `${mount}creds/otp/`)).toEqual([])
})
test('single-endpoint config round-trips (aws lease)', async (ctx) => {
if (!awsAvailable) ctx.skip()
const lease = ENGINES.aws.configs[1]
await writeConfig(client, awsMount, lease, { lease: '30m', lease_max: '2h' })
expect(await readConfig(client, awsMount, lease)).toMatchObject({ lease: '30m0s', lease_max: '2h0m0s' })
})
})
describe('grants on dynamic roles match what OpenBao enforces', () => {
const polName = `it-dyn-${sfx}`
const ca = ENGINES.ssh.configs[0]
let token: Awaited<ReturnType<typeof createToken>>
beforeAll(async () => {
const role = emptyDraft(kind)
role.values.allow_user_certificates = true
role.values.allowed_users = '*'
role.values.default_user = 'alice'
for (const name of ['granted', 'other']) await writeRole(client, mount, kind, name, payloadFromDraft(kind, role))
await runAction(client, mount, ca.actions![0])
const grants = dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length)
await client.request('PUT', `sys/policies/acl/${polName}`, { policy: renderManagedPolicy('user', 'x', grants) })
token = await createToken(client, { displayName: polName, policies: [polName], renewable: false, orphan: false })
})
afterAll(async () => {
await revokeToken(client, token.accessor).catch(() => {})
await client.request('DELETE', `sys/policies/acl/${polName}`).catch(() => {})
})
test('capabilities-self agrees with the access model for granted and other roles', async () => {
const as = client.withToken(token.token)
const hcl = renderManagedPolicy('user', 'x', dynamicGrantRules(kind, mount, 'granted', ['generate', 'manage']).filter((g) => g.capabilities.length))
const who = [{ kind: 'user' as const, name: 'x', policies: [polName] }]
for (const role of ['granted', 'other']) {
for (const path of [`${mount}sign/${role}`, `${mount}creds/${role}`, `${mount}roles/${role}`]) {
const real = (await capabilitiesSelf(as, path)).filter((c) => c !== 'deny').sort()
const modelled = accessForPath(who, [{ name: polName, hcl }], path, pathMatches).flatMap((e) => e.capabilities).sort()
expect(modelled, path).toEqual(real)
}
}
})
test('the granted token can sign with its role and not with another', async () => {
const as = client.withToken(token.token)
const out = await generateCreds(as, mount, kind.creds[0], 'granted', { public_key: PUBLIC_KEY })
expect(String(out.data.signed_key)).toContain('cert-v01')
await expect(generateCreds(as, mount, kind.creds[0], 'other', { public_key: PUBLIC_KEY })).rejects.toThrow()
expect(await listRoles(as, mount, kind)).toEqual(expect.arrayContaining(['granted']))
})
})
+101
View File
@@ -0,0 +1,101 @@
import { expect, test, vi } from 'vitest'
import { BaoClient } from '../bao'
import { ENGINES, engineFor, mountKind } from './registry'
import { deleteRole, draftFromRole, emptyDraft, listRoles, payloadFromDraft, readRole, writeRole } from './roles'
const dbRole = ENGINES.database.roleKinds[0]
const awsRole = ENGINES.aws.roleKinds[0]
const sshRole = ENGINES.ssh.roleKinds[0]
test('classifies mounts', () => {
expect(mountKind({ path: 'secret/', type: 'kv', version: '2' })).toBe('kv')
expect(mountKind({ path: 'old/', type: 'kv', version: '1' })).toBeNull()
expect(mountKind({ path: 'cubbyhole/', type: 'cubbyhole' })).toBeNull()
expect(mountKind({ path: 'database/', type: 'database' })).toBe('dynamic')
expect(mountKind({ path: 'pki/', type: 'pki' })).toBe('dynamic')
})
test('unknown engines fall back to a raw JSON role editor', () => {
const e = engineFor('pki')
expect(e.label).toBe('pki')
expect(e.roleKinds[0].fields).toEqual([])
})
test('database role round-trips through the form, keeping unknown fields', () => {
const data = {
db_name: 'pg',
creation_statements: ['CREATE ROLE "{{name}}" LOGIN;', 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "{{name}}";'],
default_ttl: 3600,
max_ttl: 0,
credential_type: 'password',
}
const draft = draftFromRole(dbRole, 'ro', data)
expect(draft.values.default_ttl).toBe('3600s')
expect(draft.values.max_ttl).toBe('')
expect(draft.extras).toEqual({ credential_type: 'password' })
draft.values.max_ttl = '24h'
expect(payloadFromDraft(dbRole, draft)).toEqual({
db_name: 'pg',
creation_statements: data.creation_statements,
revocation_statements: [],
renew_statements: [],
rollback_statements: [],
default_ttl: '3600s',
max_ttl: '24h',
credential_type: 'password',
})
})
test('statements split on blank lines, lists on commas or newlines', () => {
const d = emptyDraft(dbRole)
d.values.db_name = 'pg'
d.values.creation_statements = 'CREATE ROLE a,\n LOGIN;\n\nGRANT x;'
expect(payloadFromDraft(dbRole, d).creation_statements).toEqual(['CREATE ROLE a,\n LOGIN;', 'GRANT x;'])
const a = emptyDraft(awsRole)
a.values.policy_arns = 'arn:1, arn:2\narn:3'
expect(payloadFromDraft(awsRole, a).policy_arns).toEqual(['arn:1', 'arn:2', 'arn:3'])
})
test('required fields are enforced', () => {
expect(() => payloadFromDraft(dbRole, emptyDraft(dbRole))).toThrow('Database config name is required.')
const d = emptyDraft(dbRole)
d.values.db_name = 'pg'
expect(() => payloadFromDraft(dbRole, d)).toThrow('Creation statements is required.')
})
test('select defaults to the first option and booleans are sent as booleans', () => {
const d = emptyDraft(sshRole)
expect(d.values.key_type).toBe('ca')
d.values.allow_user_certificates = true
const body = payloadFromDraft(sshRole, d)
expect(body).toMatchObject({ key_type: 'ca', allow_user_certificates: true, allow_host_certificates: false })
expect(body).not.toHaveProperty('ttl')
})
test('generic roles are raw JSON and must be objects', () => {
const kind = engineFor('pki').roleKinds[0]
const d = emptyDraft(kind)
d.json = '{"allowed_domains":"example.com"}'
expect(payloadFromDraft(kind, d)).toEqual({ allowed_domains: 'example.com' })
d.json = '{nope'
expect(() => payloadFromDraft(kind, d)).toThrow('not valid JSON')
d.json = '[]'
expect(() => payloadFromDraft(kind, d)).toThrow('must be a JSON object')
})
test('role API calls use the mount, kind path and an encoded name', async () => {
const c = new BaoClient('http://b', 't')
const req = vi.spyOn(c, 'request').mockResolvedValue({ data: { db_name: 'pg' } })
vi.spyOn(c, 'list').mockResolvedValue(['b', 'a'])
expect(await listRoles(c, 'database/', dbRole)).toEqual(['a', 'b'])
expect(c.list).toHaveBeenCalledWith('database/roles')
expect(await readRole(c, 'database/', dbRole, 'my role')).toEqual({ db_name: 'pg' })
expect(req).toHaveBeenCalledWith('GET', 'database/roles/my%20role')
await writeRole(c, 'database/', dbRole, 'ro', { db_name: 'pg' })
expect(req).toHaveBeenCalledWith('POST', 'database/roles/ro', { db_name: 'pg' })
await deleteRole(c, 'database/', ENGINES.database.roleKinds[1], 'svc')
expect(req).toHaveBeenCalledWith('DELETE', 'database/static-roles/svc')
})
+112
View File
@@ -0,0 +1,112 @@
import type { BaoClient } from '../bao'
import type { FieldDef, RoleKind } from './registry'
/** Anything with a field schema: a role kind, a config kind, or a credential request. */
export interface Schema {
fields: FieldDef[]
}
const enc = encodeURIComponent
export type RoleData = Record<string, unknown>
export type DraftValue = string | boolean
export interface RoleDraft {
name: string
isNew: boolean
/** Values for the schema fields, keyed by field key. */
values: Record<string, DraftValue>
/** Raw JSON body, used when the role kind has no field schema. */
json: string
/** Fields OpenBao returned that the schema does not know about; written back unchanged so edits don't drop them. */
extras: RoleData
}
export async function listRoles(c: BaoClient, mount: string, kind: RoleKind): Promise<string[]> {
return (await c.list(`${mount}${kind.path}`)).sort((a, b) => a.localeCompare(b))
}
export async function readRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise<RoleData> {
const res = await c.request<{ data: RoleData }>('GET', `${mount}${kind.path}/${enc(name)}`)
return res.data
}
export async function writeRole(c: BaoClient, mount: string, kind: RoleKind, name: string, body: RoleData): Promise<void> {
await c.request('POST', `${mount}${kind.path}/${enc(name)}`, body)
}
export async function deleteRole(c: BaoClient, mount: string, kind: RoleKind, name: string): Promise<void> {
await c.request('DELETE', `${mount}${kind.path}/${enc(name)}`)
}
const listText = (v: unknown, sep: string) => (Array.isArray(v) ? v.join(sep) : typeof v === 'string' ? v : '')
function fieldToDraft(f: FieldDef, v: unknown): DraftValue {
switch (f.type) {
case 'bool':
return v === true
case 'ttl':
// OpenBao reports durations as seconds; 0 means "unset / use default".
return typeof v === 'number' ? (v > 0 ? `${v}s` : '') : typeof v === 'string' ? v : ''
case 'secret':
return ''
case 'list':
return listText(v, ', ')
case 'statements':
return listText(v, '\n\n')
default:
return typeof v === 'string' ? v : v == null ? '' : String(v)
}
}
export function emptyDraft(kind: Schema): RoleDraft {
const values: Record<string, DraftValue> = {}
for (const f of kind.fields) values[f.key] = f.type === 'bool' ? false : f.type === 'select' ? (f.options?.[0] ?? '') : ''
return { name: '', isNew: true, values, json: '{\n}', extras: {} }
}
export function draftFromRole(kind: Schema, name: string, data: RoleData): RoleDraft {
const known = new Set(kind.fields.map((f) => f.key))
const values: Record<string, DraftValue> = {}
for (const f of kind.fields) values[f.key] = fieldToDraft(f, data[f.key])
const extras = Object.fromEntries(Object.entries(data).filter(([k]) => !known.has(k)))
return { name, isNew: false, values, json: JSON.stringify(data, null, 2), extras }
}
const splitList = (s: string) =>
s
.split(/[,\n]/)
.map((x) => x.trim())
.filter(Boolean)
const splitStatements = (s: string) =>
s
.split(/\n\s*\n/)
.map((x) => x.trim())
.filter(Boolean)
/** Request body for a role write. Throws an Error with a user-facing message for invalid input. */
export function payloadFromDraft(kind: Schema, draft: RoleDraft): RoleData {
if (kind.fields.length === 0) {
let parsed: unknown
try {
parsed = JSON.parse(draft.json)
} catch {
throw new Error('Role body is not valid JSON.')
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Role body must be a JSON object.')
return parsed as RoleData
}
const body: RoleData = { ...draft.extras }
for (const f of kind.fields) {
const v = draft.values[f.key]
if (f.type === 'bool') body[f.key] = v === true
else if (f.type === 'list') body[f.key] = splitList(String(v))
else if (f.type === 'statements') body[f.key] = splitStatements(String(v))
else if (String(v).trim() !== '') body[f.key] = String(v).trim()
else if (f.required) throw new Error(`${f.label} is required.`)
else delete body[f.key]
if ((f.type === 'list' || f.type === 'statements') && f.required && (body[f.key] as string[]).length === 0) {
throw new Error(`${f.label} is required.`)
}
}
return body
}
+99
View File
@@ -0,0 +1,99 @@
import { afterAll, describe, expect, test } from 'vitest'
import { BaoClient } from './bao'
import { generateCreds } from './engines/creds'
import { lookupLease } from './engines/leases'
import { MOUNT_TYPES } from './engines/registry'
import { emptyDraft, payloadFromDraft, writeRole } from './engines/roles'
import { createMount, deleteMount, mountImpact, PartialMountError, readKvConfig, tuneMount } from './mounts'
import { listMounts } from './secrets'
import { ENGINES } from './engines/registry'
// Mounts and unmounts real engines, so run against a throwaway server (see README).
const client = new BaoClient(process.env.BAO_ADDR ?? 'http://127.0.0.1:8200', process.env.BAO_TOKEN ?? 'root')
const sfx = Math.random().toString(36).slice(2, 8)
const kv = MOUNT_TYPES.find((t) => t.type === 'kv')!
const ssh = MOUNT_TYPES.find((t) => t.type === 'ssh')!
const made: string[] = []
const find = async (path: string) => (await listMounts(client)).find((m) => m.path === path)
afterAll(async () => {
for (const p of made) await deleteMount(client, p).catch(() => {})
})
describe('mount management', () => {
test('creates a KV v2 store with settings, and reads them back', async () => {
const path = `it-kv-${sfx}`
made.push(path)
await createMount(client, path, kv, { description: 'scratch store', max_versions: '4', cas_required: true, delete_version_after: '48h' })
const m = await find(`${path}/`)
expect(m).toMatchObject({ type: 'kv', version: '2', description: 'scratch store' })
expect(await readKvConfig(client, path)).toMatchObject({ max_versions: 4, cas_required: true, delete_version_after: '48h0m0s' })
})
test('tunes a mount: description, TTLs and KV settings', async () => {
const path = `it-kv-${sfx}`
await tuneMount(client, path, kv, { description: 'renamed', max_versions: '9', cas_required: false })
expect(await find(`${path}/`)).toMatchObject({ description: 'renamed' })
expect(await readKvConfig(client, path)).toMatchObject({ max_versions: 9, cas_required: false })
})
test('lease TTLs are stored as set, and a blank TTL resets to the system default (0)', async () => {
const path = `it-ssh-${sfx}`
made.push(path)
await createMount(client, path, ssh, { description: 'hosts', default_lease_ttl: '1h', max_lease_ttl: '8h' })
expect(await find(`${path}/`)).toMatchObject({ type: 'ssh', description: 'hosts', defaultLeaseTtl: 3600, maxLeaseTtl: 28800 })
// saving the form back unchanged must not pin anything else
await tuneMount(client, path, ssh, { description: 'hosts', default_lease_ttl: '3600s', max_lease_ttl: '28800s' })
expect(await find(`${path}/`)).toMatchObject({ defaultLeaseTtl: 3600, maxLeaseTtl: 28800 })
await tuneMount(client, path, ssh, { description: 'hosts' })
expect(await find(`${path}/`)).toMatchObject({ defaultLeaseTtl: 0, maxLeaseTtl: 0 })
})
test('refuses a path that is already mounted, and creates nothing else', async () => {
await expect(createMount(client, `it-ssh-${sfx}`, ssh, {})).rejects.toThrow(/already in use|existing mount/i)
})
test('KV settings that fail after the mount exists are reported as a partial create', async () => {
// an unparseable duration is rejected by the KV engine itself, after sys/mounts has succeeded
const path = `it-partial-${sfx}`
made.push(path)
const err = await createMount(client, path, kv, { delete_version_after: 'banana' }).catch((e: unknown) => e)
expect(err).toBeInstanceOf(PartialMountError)
expect(await find(`${path}/`)).toBeDefined()
})
test('impact counts what is in a mount without reading values', async () => {
const path = `it-kv-${sfx}`
await client.request('POST', `${path}/data/a/b`, { data: { k: 'v' } })
await client.request('POST', `${path}/data/top`, { data: { k: 'v' } })
expect(await mountImpact(client, `${path}/`, 'kv')).toEqual({ kind: 'kv', topLevelEntries: 2, unknown: [] })
})
test('deleting a mount removes it and revokes the leases it issued', async () => {
const path = `it-lease-${sfx}`
made.push(path)
await createMount(client, path, ssh, {})
const role = ENGINES.ssh.roleKinds[0]
const draft = emptyDraft(role)
draft.values.key_type = 'otp'
draft.values.default_user = 'alice'
draft.values.cidr_list = '10.0.0.0/8'
await writeRole(client, `${path}/`, role, 'otp', payloadFromDraft(role, draft))
const creds = await generateCreds(client, `${path}/`, role.creds[1], 'otp', { ip: '10.1.1.1' })
expect(await mountImpact(client, `${path}/`, 'ssh')).toEqual({ kind: 'dynamic', roles: 1, hasLeases: true, unknown: [] })
expect((await lookupLease(client, creds.leaseId)).id).toBe(creds.leaseId)
await deleteMount(client, path)
expect(await find(`${path}/`)).toBeUndefined()
await expect(lookupLease(client, creds.leaseId)).rejects.toThrow()
})
test('deleting removes the KV store and its data', async () => {
const path = `it-kv-${sfx}`
await deleteMount(client, path)
expect(await find(`${path}/`)).toBeUndefined()
})
})
+101
View File
@@ -0,0 +1,101 @@
import { expect, test, vi } from 'vitest'
import { BaoClient } from './bao'
import { MOUNT_TYPES, mountTypeFor } from './engines/registry'
import * as leases from './engines/leases'
import * as roles from './engines/roles'
import { createMount, deleteMount, mountImpact, PartialMountError, readKvConfig, tuneMount } from './mounts'
import * as secrets from './secrets'
const kv = MOUNT_TYPES.find((t) => t.type === 'kv')!
const ssh = MOUNT_TYPES.find((t) => t.type === 'ssh')!
const client = () => new BaoClient('http://b', 't')
test('knows which engines it can mount', () => {
expect(MOUNT_TYPES.map((t) => t.type)).toEqual(['kv', 'database', 'aws', 'ssh'])
expect(mountTypeFor({ type: 'ssh' })).toBe(ssh)
expect(mountTypeFor({ type: 'pki' })).toBeNull()
})
test('creates a dynamic mount with its lease TTLs, leaving them out when blank', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await createMount(c, 'my-ssh', ssh, { description: 'hosts', default_lease_ttl: '1h', max_lease_ttl: '8h' })
expect(req).toHaveBeenCalledWith('POST', 'sys/mounts/my-ssh', {
type: 'ssh',
description: 'hosts',
config: { default_lease_ttl: '1h', max_lease_ttl: '8h' },
})
await createMount(c, 'plain/', ssh, {})
expect(req).toHaveBeenLastCalledWith('POST', 'sys/mounts/plain', { type: 'ssh', description: '' })
})
test('creating KV v2 mounts version 2, then saves the KV settings on the mount', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await createMount(c, 'team/store', kv, { description: 'd', max_versions: '5', cas_required: true, delete_version_after: '720h' })
expect(req).toHaveBeenNthCalledWith(1, 'POST', 'sys/mounts/team/store', { type: 'kv', description: 'd', options: { version: '2' } })
expect(req).toHaveBeenNthCalledWith(2, 'POST', 'team/store/config', { max_versions: 5, cas_required: true, delete_version_after: '720h' })
})
test('if saving KV settings fails the error says the mount exists', async () => {
const c = client()
vi.spyOn(c, 'request').mockImplementation(async (_m, path) => {
if (path.endsWith('/config')) throw new Error('permission denied')
})
const err = await createMount(c, 'store', kv, { cas_required: true }).catch((e: unknown) => e)
expect(err).toBeInstanceOf(PartialMountError)
expect((err as Error).message).toBe('store/ was mounted, but saving its KV settings failed: permission denied')
})
test('a failed mount does not try the KV settings', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockRejectedValue(new Error('path is already in use'))
await expect(createMount(c, 'store', kv, { cas_required: true })).rejects.toThrow('already in use')
expect(req).toHaveBeenCalledTimes(1)
})
test('tuning sends 0 for a blank TTL so it resets to the system default', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await tuneMount(c, 'database/', MOUNT_TYPES[1], { description: 'x', default_lease_ttl: '2h' })
expect(req).toHaveBeenCalledWith('POST', 'sys/mounts/database/tune', { description: 'x', default_lease_ttl: '2h', max_lease_ttl: '0' })
})
test('tuning KV updates the description and the KV settings, with no TTLs', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue(undefined)
await tuneMount(c, 'secret/', kv, { description: 'kv', max_versions: '10', cas_required: false })
expect(req).toHaveBeenNthCalledWith(1, 'POST', 'sys/mounts/secret/tune', { description: 'kv' })
expect(req).toHaveBeenNthCalledWith(2, 'POST', 'secret/config', { max_versions: 10, cas_required: false })
})
test('delete and KV config read use the mount path', async () => {
const c = client()
const req = vi.spyOn(c, 'request').mockResolvedValue({ data: { max_versions: 3 } })
await deleteMount(c, 'team/store/')
expect(req).toHaveBeenCalledWith('DELETE', 'sys/mounts/team/store')
expect(await readKvConfig(c, 'team/store')).toEqual({ max_versions: 3 })
expect(req).toHaveBeenLastCalledWith('GET', 'team/store/config')
})
test('impact of deleting a KV mount counts top-level entries', async () => {
vi.spyOn(secrets, 'listSecrets').mockResolvedValue([
{ name: 'a/', path: 'a/', isFolder: true },
{ name: 'b', path: 'b', isFolder: false },
])
expect(await mountImpact(client(), 'secret/', 'kv')).toEqual({ kind: 'kv', topLevelEntries: 2, unknown: [] })
})
test('impact of deleting a dynamic mount counts roles and notes leases', async () => {
vi.spyOn(roles, 'listRoles').mockImplementation(async (_c, _m, kind) => (kind.id === 'roles' ? ['ro', 'rw'] : ['svc']))
vi.spyOn(leases, 'listLeases').mockResolvedValue([{ name: 'creds/', path: 'database/creds/', isFolder: true }])
expect(await mountImpact(client(), 'database/', 'database')).toEqual({ kind: 'dynamic', roles: 3, hasLeases: true, unknown: [] })
})
test('impact reports what it was not allowed to count', async () => {
vi.spyOn(roles, 'listRoles').mockResolvedValue(['ro'])
vi.spyOn(leases, 'listLeases').mockRejectedValue(new Error('permission denied'))
expect(await mountImpact(client(), 'ssh/', 'ssh')).toEqual({ kind: 'dynamic', roles: 1, hasLeases: undefined, unknown: ['leases'] })
vi.spyOn(secrets, 'listSecrets').mockRejectedValue(new Error('permission denied'))
expect(await mountImpact(client(), 'secret/', 'kv')).toEqual({ kind: 'kv', topLevelEntries: undefined, unknown: ['secrets'] })
})
+126
View File
@@ -0,0 +1,126 @@
import type { BaoClient } from './bao'
import { engineFor, type MountType } from './engines/registry'
import { listLeases } from './engines/leases'
import { listRoles, type RoleData } from './engines/roles'
import { listSecrets } from './secrets'
const encPath = (mount: string) =>
mount
.replace(/^\/+|\/+$/g, '')
.split('/')
.map(encodeURIComponent)
.join('/')
const sysPath = (mount: string) => `sys/mounts/${encPath(mount)}`
const withSlash = (mount: string) => (mount.endsWith('/') ? mount : `${mount}/`)
/** Thrown when the mount was created but a follow-up step failed, so the caller can say the mount exists. */
export class PartialMountError extends Error {
constructor(message: string) {
super(message)
this.name = 'PartialMountError'
}
}
/** Splits form values into what sys/mounts takes and what the KV engine keeps itself. */
function split(type: MountType, body: RoleData): { sys: RoleData; kv: RoleData } {
const configKeys = new Set(type.configFields.map((f) => f.key))
const sys: RoleData = {}
const kv: RoleData = {}
for (const [k, v] of Object.entries(body)) (configKeys.has(k) ? kv : sys)[k] = v
return { sys, kv }
}
/** KV v2 sends max_versions as a number; everything else stays as the form produced it. */
function kvBody(kv: RoleData): RoleData {
const out = { ...kv }
if (typeof out.max_versions === 'string') out.max_versions = Number(out.max_versions)
return out
}
/** Mounts a secrets engine at `path`. KV v2 settings take a second call; if it fails the mount is still there. */
export async function createMount(c: BaoClient, path: string, type: MountType, body: RoleData): Promise<void> {
const { sys, kv } = split(type, body)
const config: RoleData = {}
if (sys.default_lease_ttl) config.default_lease_ttl = sys.default_lease_ttl
if (sys.max_lease_ttl) config.max_lease_ttl = sys.max_lease_ttl
await c.request('POST', sysPath(path), {
type: type.type,
description: sys.description ?? '',
...(type.options ? { options: type.options } : {}),
...(Object.keys(config).length ? { config } : {}),
})
if (Object.keys(kv).length) {
try {
await writeKvConfig(c, path, type, kv)
} catch (e) {
throw new PartialMountError(`${withSlash(path)} was mounted, but saving its KV settings failed: ${(e as Error).message}`)
}
}
}
/**
* Changes a mount's description and default/max lease TTL (and KV settings). Path and type can't change. A blank TTL
* resets to the system default, which OpenBao spells 0.
*/
export async function tuneMount(c: BaoClient, path: string, type: MountType, body: RoleData): Promise<void> {
const { sys, kv } = split(type, body)
const hasTtl = type.fields.some((f) => f.key === 'default_lease_ttl')
await c.request('POST', `${sysPath(path)}/tune`, {
description: sys.description ?? '',
...(hasTtl ? { default_lease_ttl: sys.default_lease_ttl ?? '0', max_lease_ttl: sys.max_lease_ttl ?? '0' } : {}),
})
if (Object.keys(kv).length) await writeKvConfig(c, path, type, kv)
}
/** Unmounts the engine. This permanently deletes everything stored in it and revokes every lease it issued. */
export async function deleteMount(c: BaoClient, path: string): Promise<void> {
await c.request('DELETE', sysPath(path))
}
export async function readKvConfig(c: BaoClient, mount: string): Promise<RoleData> {
const res = await c.request<{ data: RoleData }>('GET', `${withSlash(mount)}config`)
return res.data
}
async function writeKvConfig(c: BaoClient, mount: string, type: MountType, kv: RoleData): Promise<void> {
if (type.configFields.length === 0) return
await c.request('POST', `${withSlash(mount)}config`, kvBody(kv))
}
export interface MountImpact {
kind: 'kv' | 'dynamic'
/** KV: entries at the top level of the mount (folders count as one). */
topLevelEntries?: number
/** Dynamic: roles across all role kinds. */
roles?: number
/** Dynamic: whether any lease exists under the mount (they are all revoked on delete). */
hasLeases?: boolean
/** Things that could not be counted, e.g. no permission to list. */
unknown: string[]
}
/** What deleting a mount would destroy, as far as the token can see. Never reads secret values. */
export async function mountImpact(c: BaoClient, mount: string, type: string): Promise<MountImpact> {
const unknown: string[] = []
if (type === 'kv') {
const entries = await listSecrets(c, mount, '').catch(() => {
unknown.push('secrets')
return null
})
return { kind: 'kv', topLevelEntries: entries?.length, unknown }
}
const engine = engineFor(type)
let roles = 0
for (const kind of engine.roleKinds) {
roles += (await listRoles(c, mount, kind).catch(() => {
unknown.push(kind.label.toLowerCase())
return []
})).length
}
const leases = await listLeases(c, mount).catch(() => {
unknown.push('leases')
return null
})
return { kind: 'dynamic', roles, hasLeases: leases === null ? undefined : leases.length > 0, unknown }
}
+10
View File
@@ -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<string, string> } }>('GET', `secret/data/${path}`)
expect(res.data.data).toEqual({ TOKEN: 'v1' })
})
})
+51 -7
View File
@@ -14,17 +14,53 @@ export interface SecretEntry {
isFolder: boolean isFolder: boolean
} }
export async function listKvMounts(c: BaoClient): Promise<KvMount[]> { export interface Mount {
const res = await c.request<{ data: Record<string, { type: string; options?: { version?: string } | null }> }>( /** Mount path with trailing slash, e.g. "database/". */
'GET', path: string
'sys/mounts', /** Engine type as reported by sys/mounts, e.g. "kv", "database", "aws", "ssh". */
) type: string
/** KV version ("1" | "2") when the engine is KV. */
version?: string
description?: string
/**
* Seconds explicitly set on this mount, 0 when it uses the system default. (sys/mounts/<path>/tune reports the
* effective value instead, which would pin the default if it were saved back.)
*/
defaultLeaseTtl?: number
maxLeaseTtl?: number
}
/** Every secrets engine mount visible to the token, sorted by path. */
export async function listMounts(c: BaoClient): Promise<Mount[]> {
const res = await c.request<{
data: Record<
string,
{
type: string
description?: string
options?: { version?: string } | null
config?: { default_lease_ttl?: number; max_lease_ttl?: number }
}
>
}>('GET', 'sys/mounts')
return Object.entries(res.data) return Object.entries(res.data)
.filter(([, m]) => m.type === 'kv' && m.options?.version === '2') .map(([path, m]) => ({
.map(([path]) => ({ path })) path,
type: m.type,
version: m.options?.version,
description: m.description,
defaultLeaseTtl: m.config?.default_lease_ttl,
maxLeaseTtl: m.config?.max_lease_ttl,
}))
.sort((a, b) => a.path.localeCompare(b.path)) .sort((a, b) => a.path.localeCompare(b.path))
} }
export const isKvV2 = (m: Mount) => m.type === 'kv' && m.version === '2'
export async function listKvMounts(c: BaoClient): Promise<KvMount[]> {
return (await listMounts(c)).filter(isKvV2).map(({ path }) => ({ path }))
}
/** Lists metadata only; secret values are never read. `prefix` is "" or ends with "/". */ /** Lists metadata only; secret values are never read. `prefix` is "" or ends with "/". */
export async function listSecrets(c: BaoClient, mount: string, prefix: string): Promise<SecretEntry[]> { export async function listSecrets(c: BaoClient, mount: string, prefix: string): Promise<SecretEntry[]> {
const keys = await c.list(`${mount}metadata/${enc(prefix)}`) const keys = await c.list(`${mount}metadata/${enc(prefix)}`)
@@ -36,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. */ /** 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}` 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<string, string>): Promise<void> {
await c.request('POST', dataPath(mount, enc(path)), { data, options: { cas: 0 } })
}
export async function readPolicyHcl(c: BaoClient, name: string): Promise<string | null> { export async function readPolicyHcl(c: BaoClient, name: string): Promise<string | null> {
try { try {
const res = await c.request<{ data: { policy: string } }>('GET', `sys/policies/acl/${encodeURIComponent(name)}`) const res = await c.request<{ data: { policy: string } }>('GET', `sys/policies/acl/${encodeURIComponent(name)}`)
+38 -2
View File
@@ -4,11 +4,18 @@ import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao' import { BaoClient } from '../../api/bao'
import * as grants from '../../api/grants' import * as grants from '../../api/grants'
import * as roles from '../../api/engines/roles'
import * as secrets from '../../api/secrets' import * as secrets from '../../api/secrets'
import { AccessEditor } from './AccessEditor' import { AccessEditor } from './AccessEditor'
vi.mock('../../api/grants') vi.mock('../../api/grants')
vi.mock('../../api/secrets') vi.mock('../../api/engines/roles')
vi.mock('../../api/secrets', async (orig) => ({
...(await orig<typeof secrets>()),
listMounts: vi.fn(),
listSecrets: vi.fn(),
readPolicyHcl: vi.fn(),
}))
const client = new BaoClient('http://b', 't') const client = new BaoClient('http://b', 't')
const target = { kind: 'user' as const, name: 'alice' } const target = { kind: 'user' as const, name: 'alice' }
@@ -29,7 +36,7 @@ const state = (over: Partial<grants.GrantState> = {}): grants.GrantState => ({
beforeEach(() => { beforeEach(() => {
vi.mocked(grants.getGrantState).mockResolvedValue(state()) vi.mocked(grants.getGrantState).mockResolvedValue(state())
vi.mocked(secrets.listKvMounts).mockResolvedValue([{ path: 'secret/' }]) vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }])
vi.mocked(secrets.listSecrets).mockImplementation(async (_c, _m, prefix) => vi.mocked(secrets.listSecrets).mockImplementation(async (_c, _m, prefix) =>
prefix === '' prefix === ''
? [ ? [
@@ -140,3 +147,32 @@ test('shows load errors', async () => {
setup() setup()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied') expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
}) })
test('grants generate on a dynamic-engine role from the identity side', async () => {
vi.mocked(secrets.listMounts).mockResolvedValue([
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'database/', type: 'database' },
])
vi.mocked(roles.listRoles).mockResolvedValue(['readonly', 'readwrite'])
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.selectOptions(await screen.findByLabelText('Secrets engine'), 'database/')
await user.click(await screen.findByLabelText('readwrite'))
await user.click(screen.getByLabelText(/Manage role/))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, target, [
{ path: 'database/creds/readwrite', capabilities: ['read'] },
{ path: 'database/roles/readwrite', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('a dynamic grant needs a role chosen', async () => {
vi.mocked(secrets.listMounts).mockResolvedValue([{ path: 'database/', type: 'database' }])
vi.mocked(roles.listRoles).mockResolvedValue(['readonly'])
const user = setup()
await screen.findByLabelText('readonly')
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Choose a role.')
expect(grants.grantAccess).not.toHaveBeenCalled()
})
+28 -9
View File
@@ -2,13 +2,17 @@ import { useMutation, useQuery } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react' import { useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants' import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants'
import { listKvMounts, readPolicyHcl } from '../../api/secrets' import { engineFor, mountKind } from '../../api/engines/registry'
import { kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed' import { readPolicyHcl } from '../../api/secrets'
import { dynamicGrantRules, kvGrantRules, validateGrantPath, type DynamicAccess, type KvCapability } from '../../model/managed'
import { groupGrants } from '../../model/grantRows' import { groupGrants } from '../../model/grantRows'
import { CapabilityChips } from '../shared/CapabilityChips' import { CapabilityChips } from '../shared/CapabilityChips'
import { CapabilityPicker } from '../shared/CapabilityPicker' import { CapabilityPicker } from '../shared/CapabilityPicker'
import { DynamicAccessPicker } from '../shared/DynamicAccessPicker'
import { useMounts } from '../shared/useMounts'
import { useRefreshAccess } from '../shared/useRefreshAccess' import { useRefreshAccess } from '../shared/useRefreshAccess'
import { PathPicker } from './PathPicker' import { PathPicker } from './PathPicker'
import { RolePicker, type RoleSelection } from './RolePicker'
import { useConfirm } from '../shared/useConfirm' import { useConfirm } from '../shared/useConfirm'
interface Props { interface Props {
@@ -35,21 +39,29 @@ export function AccessEditor({ client, target, onClose }: Props) {
const confirm = useConfirm() const confirm = useConfirm()
const stateKey = ['grant-state', target.kind, target.name] const stateKey = ['grant-state', target.kind, target.name]
const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) }) const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) })
const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) }) const mounts = useMounts(client)
const [mountChoice, setMount] = useState<string | null>(null) const [mountChoice, setMount] = useState<string | null>(null)
const [secretPath, setSecretPath] = useState('') const [secretPath, setSecretPath] = useState('')
const [caps, setCaps] = useState<KvCapability[]>(['read']) const [caps, setCaps] = useState<KvCapability[]>(['read'])
const [roleSel, setRoleSel] = useState<RoleSelection>({ kindId: '', role: '' })
const [access, setAccess] = useState<DynamicAccess[]>(['generate'])
const [showRaw, setShowRaw] = useState(false) const [showRaw, setShowRaw] = useState(false)
const [formError, setFormError] = useState<string | null>(null) const [formError, setFormError] = useState<string | null>(null)
const mount = mountChoice ?? mounts.data?.[0]?.path ?? '' const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0]
const mount = current?.path ?? ''
const dynamic = current !== undefined && mountKind(current) === 'dynamic'
const engine = dynamic ? engineFor(current.type) : null
const roleKind = engine ? (engine.roleKinds.find((k) => k.id === roleSel.kindId) ?? engine.roleKinds[0]) : null
const done = useRefreshAccess() const done = useRefreshAccess()
const grant = useMutation({ const grant = useMutation({
mutationFn: () => grantAccess(client, target, kvGrantRules(mount, secretPath, caps)), mutationFn: () =>
grantAccess(client, target, roleKind ? dynamicGrantRules(roleKind, mount, roleSel.role, access) : kvGrantRules(mount, secretPath, caps)),
onSuccess: () => { onSuccess: () => {
setSecretPath('') setSecretPath('')
setRoleSel({ kindId: roleSel.kindId, role: '' })
return done() return done()
}, },
}) })
@@ -57,7 +69,10 @@ export function AccessEditor({ client, target, onClose }: Props) {
function submit(e: FormEvent) { function submit(e: FormEvent) {
e.preventDefault() e.preventDefault()
const err = validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null) const err = roleKind
? (roleSel.role ? validateGrantPath(`${mount}${roleKind.path}/${roleSel.role}`) : 'Choose a role.') ??
(access.length === 0 ? 'Select at least one kind of access.' : null)
: (validateGrantPath(secretPath) ?? (caps.length === 0 ? 'Select at least one capability.' : null))
setFormError(err) setFormError(err)
if (!err) grant.mutate() if (!err) grant.mutate()
} }
@@ -163,6 +178,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
onChange={(e) => { onChange={(e) => {
setMount(e.target.value) setMount(e.target.value)
setSecretPath('') setSecretPath('')
setRoleSel({ kindId: '', role: '' })
}} }}
> >
{mounts.data?.map((m) => ( {mounts.data?.map((m) => (
@@ -170,10 +186,13 @@ export function AccessEditor({ client, target, onClose }: Props) {
))} ))}
</select> </select>
</label> </label>
{mount && <PathPicker key={mount} client={client} mount={mount} value={secretPath} onChange={setSecretPath} />} {mount && engine && <RolePicker key={mount} client={client} mount={mount} engine={engine} value={roleSel} onChange={setRoleSel} />}
<CapabilityPicker value={caps} onChange={setCaps} /> {mount && !engine && <PathPicker key={mount} client={client} mount={mount} value={secretPath} onChange={setSecretPath} />}
{engine ? <DynamicAccessPicker value={access} onChange={setAccess} /> : <CapabilityPicker value={caps} onChange={setCaps} />}
<p className="hint"> <p className="hint">
Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path. {engine
? 'Granting a role that already has a grant replaces its access. Unticked access is removed.'
: 'Granting a path that already has a grant replaces its capabilities. “list” applies to the secret’s metadata path.'}
</p> </p>
{(formError || grant.error) && <p role="alert">{formError ?? grant.error?.message}</p>} {(formError || grant.error) && <p role="alert">{formError ?? grant.error?.message}</p>}
<button type="submit" disabled={grant.isPending || !mount}> <button type="submit" disabled={grant.isPending || !mount}>
+80
View File
@@ -0,0 +1,80 @@
import { useQuery } from '@tanstack/react-query'
import { useId } from 'react'
import type { BaoClient } from '../../api/bao'
import type { EngineDef } from '../../api/engines/registry'
import { listRoles } from '../../api/engines/roles'
export interface RoleSelection {
kindId: string
/** A role name, "*" for every role of the kind, or "" for none chosen yet. */
role: string
}
/** Pick a role of a dynamic engine (or all of them) to grant access to. Lists role names only. */
export function RolePicker({
client,
mount,
engine,
value,
onChange,
}: {
client: BaoClient
mount: string
engine: EngineDef
value: RoleSelection
onChange: (v: RoleSelection) => void
}) {
const id = useId()
const kind = engine.roleKinds.find((k) => k.id === value.kindId) ?? engine.roleKinds[0]
const roles = useQuery({ queryKey: ['engine-roles', mount, kind.id], queryFn: () => listRoles(client, mount, kind) })
const all = value.role === '*'
return (
<fieldset className="path-picker">
<legend>Role</legend>
{engine.roleKinds.length > 1 && (
<label>
Role type
<select value={kind.id} onChange={(e) => onChange({ kindId: e.target.value, role: '' })}>
{engine.roleKinds.map((k) => (
<option key={k.id} value={k.id}>
{k.label}
</option>
))}
</select>
</label>
)}
{roles.isPending && <p className="hint">Loading…</p>}
{roles.error && <p role="alert">Can’t list roles here: {roles.error.message}</p>}
{roles.data?.length === 0 && <p className="hint">No roles in {mount}{kind.path} yet.</p>}
{!!roles.data?.length && (
<ul className="entries" aria-label={`Roles in ${mount}`}>
{roles.data.map((name) => (
<li key={name}>
<label className="entry-secret">
<input
type="radio"
name={`${id}-role`}
checked={value.role === name}
disabled={all}
onChange={() => onChange({ kindId: kind.id, role: name })}
/>
{name}
</label>
</li>
))}
</ul>
)}
<label className="check">
<input
type="checkbox"
checked={all}
onChange={(e) => onChange({ kindId: kind.id, role: e.target.checked ? '*' : '' })}
/>
<span>
Every role in <code>{mount}{kind.path}</code>, including ones added later
</span>
</label>
</fieldset>
)
}
+6 -2
View File
@@ -4,6 +4,10 @@ export interface GrantEdgeData {
label: string label: string
/** Vertical nudge so labels on edges into the same node don't sit on top of each other. */ /** Vertical nudge so labels on edges into the same node don't sit on top of each other. */
offset: number offset: number
/** Touches the selected node. */
linked?: boolean
/** Another node is selected and this edge isn't one of its links. */
dim?: boolean
onSelect: () => void onSelect: () => void
} }
@@ -12,7 +16,7 @@ export interface GrantEdgeData {
* fanned out to different rows, instead of at the midpoint where edges from one policy bunch up. * fanned out to different rows, instead of at the midpoint where edges from one policy bunch up.
*/ */
export function GrantEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, selected, data }: EdgeProps) { export function GrantEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, markerEnd, selected, data }: EdgeProps) {
const { label, offset, onSelect } = data as unknown as GrantEdgeData const { label, offset, linked, dim, onSelect } = data as unknown as GrantEdgeData
const [path] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition }) const [path] = getBezierPath({ sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition })
return ( return (
<> <>
@@ -20,7 +24,7 @@ export function GrantEdge({ id, sourceX, sourceY, targetX, targetY, sourcePositi
<EdgeLabelRenderer> <EdgeLabelRenderer>
<button <button
type="button" type="button"
className={`nodrag nopan edge-label${selected ? ' edge-label-selected' : ''}`} className={`nodrag nopan edge-label${selected ? ' edge-label-selected' : ''}${linked ? ' edge-label-linked' : ''}${dim ? ' edge-label-dim' : ''}`}
style={{ transform: `translate(-100%, -50%) translate(${targetX - 18}px, ${targetY + offset}px)` }} style={{ transform: `translate(-100%, -50%) translate(${targetX - 18}px, ${targetY + offset}px)` }}
onClick={onSelect} onClick={onSelect}
> >
+35 -4
View File
@@ -16,19 +16,19 @@ import { GraphPage } from './GraphPage'
// jsdom can't lay out React Flow, so render nodes/edges as plain buttons that fire the same callbacks. // jsdom can't lay out React Flow, so render nodes/edges as plain buttons that fire the same callbacks.
vi.mock('@xyflow/react', () => ({ vi.mock('@xyflow/react', () => ({
ReactFlow: (p: { ReactFlow: (p: {
nodes: { id: string; data: { label: string } }[] nodes: { id: string; className?: string; data: { label: string } }[]
edges: { id: string; label?: string }[] edges: { id: string; className?: string; label?: string }[]
onNodeClick: (e: unknown, n: { id: string }) => void onNodeClick: (e: unknown, n: { id: string }) => void
onEdgeClick: (e: unknown, ed: { id: string }) => void onEdgeClick: (e: unknown, ed: { id: string }) => void
}) => ( }) => (
<div> <div>
{p.nodes.map((n) => ( {p.nodes.map((n) => (
<button key={n.id} type="button" onClick={(e) => p.onNodeClick(e, n)}> <button key={n.id} type="button" data-class={n.className} onClick={(e) => p.onNodeClick(e, n)}>
node {n.data.label} node {n.data.label}
</button> </button>
))} ))}
{p.edges.map((ed) => ( {p.edges.map((ed) => (
<button key={ed.id} type="button" onClick={(e) => p.onEdgeClick(e, ed)}> <button key={ed.id} type="button" data-class={ed.className} onClick={(e) => p.onEdgeClick(e, ed)}>
edge {ed.id} edge {ed.id}
</button> </button>
))} ))}
@@ -140,3 +140,34 @@ test('grants in unmanaged policies cannot be revoked', async () => {
expect(screen.queryByRole('button', { name: 'Revoke' })).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: 'Revoke' })).not.toBeInTheDocument()
expect(screen.getByText(/does not manage/)).toBeInTheDocument() expect(screen.getByText(/does not manage/)).toBeInTheDocument()
}) })
const cls = (name: string) => screen.getByRole('button', { name }).getAttribute('data-class') ?? ''
test('selecting a node highlights its links and dims the rest', async () => {
const user = await open()
// nothing is dimmed until something is selected
expect(cls('node bob')).not.toContain('gnode-dim')
expect(cls('edge policy:legacy->path:secret/data/other')).not.toContain('edge-')
await user.click(screen.getByRole('button', { name: 'node envbao-user-alice' }))
// its links, in and out, are highlighted, with the boxes at their far ends
expect(cls('edge policy:envbao-user-alice->path:secret/data/app/*')).toContain('edge-linked')
expect(cls('edge identity:user:alice->policy:envbao-user-alice')).toContain('edge-linked')
expect(cls('node alice')).toContain('gnode-linked')
expect(cls('node secret/data/app/*')).toContain('gnode-linked')
expect(cls('node envbao-user-alice')).toContain('gnode-selected')
// an unrelated chain steps back
expect(cls('edge policy:legacy->path:secret/data/other')).toContain('edge-dim')
expect(cls('node bob')).toContain('gnode-dim')
expect(cls('node legacy')).toContain('gnode-dim')
})
test('clearing the selection, or selecting an edge, removes the highlight', async () => {
const user = await open()
await user.click(screen.getByRole('button', { name: 'node alice' }))
expect(cls('node bob')).toContain('gnode-dim')
await user.click(screen.getByRole('button', { name: 'edge policy:legacy->path:secret/data/other' }))
expect(cls('node bob')).not.toContain('gnode-dim')
expect(cls('edge policy:envbao-user-alice->path:secret/data/app/*')).not.toContain('edge-dim')
})
+11
View File
@@ -34,6 +34,11 @@ function capabilityLabel(caps: string[] | undefined): string | undefined {
function toFlow(graph: AccessGraph, selected: Selection | null, onEdgeSelect: (id: string) => void): { nodes: Node[]; edges: Edge[] } { function toFlow(graph: AccessGraph, selected: Selection | null, onEdgeSelect: (id: string) => void): { nodes: Node[]; edges: Edge[] } {
const pos = layoutColumns(graph) const pos = layoutColumns(graph)
// Selecting a node highlights every edge into or out of it, and the boxes at their far ends.
const focus = selected?.kind === 'node' ? selected.id : null
const linkedEdges = new Set(graph.edges.filter((e) => e.source === focus || e.target === focus).map((e) => e.id))
const linkedNodes = new Set<string>(focus ? [focus] : [])
for (const e of graph.edges) if (linkedEdges.has(e.id)) linkedNodes.add(e.source).add(e.target)
const nodes: Node[] = graph.nodes.map((n) => ({ const nodes: Node[] = graph.nodes.map((n) => ({
id: n.id, id: n.id,
position: pos.get(n.id)!, position: pos.get(n.id)!,
@@ -45,6 +50,8 @@ function toFlow(graph: AccessGraph, selected: Selection | null, onEdgeSelect: (i
n.type === 'policy' && n.missing ? 'gnode-missing' : '', n.type === 'policy' && n.missing ? 'gnode-missing' : '',
n.type === 'policy' && n.managed ? 'gnode-managed' : '', n.type === 'policy' && n.managed ? 'gnode-managed' : '',
selected?.kind === 'node' && selected.id === n.id ? 'gnode-selected' : '', selected?.kind === 'node' && selected.id === n.id ? 'gnode-selected' : '',
focus && n.id !== focus && linkedNodes.has(n.id) ? 'gnode-linked' : '',
focus && !linkedNodes.has(n.id) ? 'gnode-dim' : '',
].join(' '), ].join(' '),
sourcePosition: Position.Right, sourcePosition: Position.Right,
targetPosition: Position.Left, targetPosition: Position.Left,
@@ -59,6 +66,8 @@ function toFlow(graph: AccessGraph, selected: Selection | null, onEdgeSelect: (i
target: e.target, target: e.target,
markerEnd: { type: MarkerType.ArrowClosed }, markerEnd: { type: MarkerType.ArrowClosed },
selected: selected?.kind === 'edge' && selected.id === e.id, selected: selected?.kind === 'edge' && selected.id === e.id,
className: focus ? (linkedEdges.has(e.id) ? 'edge-linked' : 'edge-dim') : undefined,
zIndex: linkedEdges.has(e.id) ? 1 : 0,
} }
const label = capabilityLabel(e.capabilities) const label = capabilityLabel(e.capabilities)
if (!label) return base if (!label) return base
@@ -66,6 +75,8 @@ function toFlow(graph: AccessGraph, selected: Selection | null, onEdgeSelect: (i
const data: GrantEdgeData = { const data: GrantEdgeData = {
label, label,
offset: (siblings.indexOf(e.id) - (siblings.length - 1) / 2) * 24, offset: (siblings.indexOf(e.id) - (siblings.length - 1) / 2) * 24,
linked: linkedEdges.has(e.id),
dim: focus !== null && !linkedEdges.has(e.id),
onSelect: () => onEdgeSelect(e.id), onSelect: () => onEdgeSelect(e.id),
} }
return { ...base, type: 'grant', data: data as unknown as Record<string, unknown> } return { ...base, type: 'grant', data: data as unknown as Record<string, unknown> }
+14 -3
View File
@@ -64,7 +64,18 @@ export function AccessPanel({ client, mount, secret }: Props) {
) )
} }
function Entries({ data, path }: { data: NonNullable<ReturnType<typeof useAccessInputs>['data']>; path: string }) { /** Who can reach `path`, from every identity's effective policies. */
export function Entries({
data,
path,
label = 'Who can access this secret',
empty = 'No identity can reach this secret.',
}: {
data: NonNullable<ReturnType<typeof useAccessInputs>['data']>
path: string
label?: string
empty?: string
}) {
const entries = accessForPath(data.identities, data.policies, path, pathMatches) const entries = accessForPath(data.identities, data.policies, path, pathMatches)
return ( return (
<> <>
@@ -74,9 +85,9 @@ function Entries({ data, path }: { data: NonNullable<ReturnType<typeof useAccess
</p> </p>
))} ))}
{entries.length === 0 ? ( {entries.length === 0 ? (
<p>No identity can reach this secret.</p> <p>{empty}</p>
) : ( ) : (
<table aria-label="Who can access this secret"> <table aria-label={label}>
<thead> <thead>
<tr> <tr>
<th>Identity</th> <th>Identity</th>
+135
View File
@@ -0,0 +1,135 @@
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 config from '../../api/engines/config'
import { ENGINES } from '../../api/engines/registry'
import { ConfigPanel } from './ConfigPanel'
vi.mock('../../api/engines/config')
const client = new BaoClient('http://b', 't')
const conn = ENGINES.database.configs[0]
function renderPanel(type: keyof typeof ENGINES) {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<ConfigPanel client={client} mount={`${type}/`} engine={ENGINES[type]} />
</QueryClientProvider>,
)
return userEvent.setup()
}
beforeEach(() => {
vi.mocked(config.listConfigs).mockResolvedValue(['pg'])
})
afterEach(() => vi.resetAllMocks())
test('creates a database connection, sending the password only when typed', async () => {
vi.mocked(config.writeConfig).mockResolvedValue()
const user = renderPanel('database')
await user.click(await screen.findByRole('button', { name: 'New connection' }))
await user.type(screen.getByLabelText('Connection name'), 'main')
await user.type(screen.getByLabelText(/^Connection URL/), 'postgresql://u:p@db/app')
await user.type(screen.getByLabelText('Admin password'), 's3cret')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(config.writeConfig).toHaveBeenCalledWith(
client,
'database/',
conn,
expect.objectContaining({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://u:p@db/app', password: 's3cret' }),
'main',
)
})
test('editing keeps the stored password: blank is omitted and nothing is prefilled', async () => {
vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x', username: 'bao', allowed_roles: ['ro'] })
vi.mocked(config.writeConfig).mockResolvedValue()
const user = renderPanel('database')
await user.click(await screen.findByRole('button', { name: 'Edit pg' }))
expect(await screen.findByLabelText('Admin password')).toHaveValue('')
expect(screen.getByLabelText('Connection name')).toBeDisabled()
await user.click(screen.getByRole('button', { name: 'Save' }))
const body = vi.mocked(config.writeConfig).mock.calls[0][3]
expect(body).toMatchObject({ connection_url: 'postgresql://x', allowed_roles: ['ro'], username: 'bao' })
expect(body).not.toHaveProperty('password')
})
test('rotating root credentials asks first', async () => {
vi.mocked(config.readConfig).mockResolvedValue({ plugin_name: 'postgresql-database-plugin', connection_url: 'postgresql://x' })
vi.mocked(config.runAction).mockResolvedValue()
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
const user = renderPanel('database')
await user.click(await screen.findByRole('button', { name: 'Edit pg' }))
await user.click(await screen.findByRole('button', { name: 'Rotate root credentials' }))
expect(config.runAction).not.toHaveBeenCalled()
confirm.mockReturnValue(true)
await user.click(screen.getByRole('button', { name: 'Rotate root credentials' }))
expect(config.runAction).toHaveBeenCalledWith(client, 'database/', conn.actions![0], 'pg')
})
test('aws shows root and lease configs, loaded from their own endpoints', async () => {
vi.mocked(config.readConfig).mockImplementation(async (_c, _m, kind) =>
kind.id === 'root' ? { access_key: 'AKIA1', region: 'eu-west-1' } : null,
)
renderPanel('aws')
expect(await screen.findByDisplayValue('AKIA1')).toBeInTheDocument()
expect(screen.getByLabelText('Secret key')).toHaveValue('')
expect(screen.getByLabelText('Default lease')).toBeInTheDocument()
})
test('ssh CA: shows the public key and generating asks first', async () => {
vi.mocked(config.readConfig).mockResolvedValue({ public_key: 'ssh-rsa AAAAca' })
vi.mocked(config.runAction).mockResolvedValue()
vi.spyOn(window, 'confirm').mockReturnValue(true)
const user = renderPanel('ssh')
expect(await screen.findByLabelText('Current CA public key')).toHaveValue('ssh-rsa AAAAca')
await user.click(screen.getByRole('button', { name: 'Generate signing key' }))
expect(config.runAction).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.configs[0].actions![0], undefined)
})
test('shows the load error', async () => {
vi.mocked(config.listConfigs).mockRejectedValue(new Error('permission denied'))
renderPanel('database')
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
test('the connections table shows each connection\'s URL and allowed roles, hiding literal passwords', async () => {
vi.mocked(config.listConfigs).mockResolvedValue(['main', 'legacy', 'bare'])
vi.mocked(config.readConfig).mockImplementation(async (_c, _m, _k, name) =>
name === 'main'
? { connection_url: 'postgresql://{{username}}:{{password}}@db:5432/app', allowed_roles: ['readonly', 'readwrite'] }
: name === 'legacy'
? { connection_url: 'postgresql://bao:hunter2@old:5432/app', allowed_roles: ['*'] }
: { allowed_roles: [] },
)
renderPanel('database')
const table = await screen.findByRole('table', { name: 'Connections' })
expect(within(table).getAllByRole('columnheader').map((h) => h.textContent)).toEqual(['Name', 'Connection URL', 'Allowed roles', ''])
const main = (await within(table).findByText('main')).closest('tr')!
expect(await within(main).findByText('postgresql://{{username}}:{{password}}@db:5432/app')).toBeInTheDocument()
expect(within(main).getByText('readonly')).toBeInTheDocument()
expect(within(main).getByText('readwrite')).toBeInTheDocument()
const legacy = within(table).getByText('legacy').closest('tr')!
expect(await within(legacy).findByText('postgresql://bao:••••@old:5432/app')).toBeInTheDocument()
expect(table).not.toHaveTextContent('hunter2')
expect(within(legacy).getByText('*')).toBeInTheDocument()
const bare = within(table).getByText('bare').closest('tr')!
expect((await within(bare).findAllByText('None')).length).toBe(2)
})
test('a connection that cannot be read says why, without hiding the others', async () => {
vi.mocked(config.listConfigs).mockResolvedValue(['ok', 'broken'])
vi.mocked(config.readConfig).mockImplementation(async (_c, _m, _k, name) => {
if (name === 'broken') throw new Error('permission denied')
return { connection_url: 'postgresql://db/app', allowed_roles: ['ro'] }
})
renderPanel('database')
expect(await screen.findByText('postgresql://db/app')).toBeInTheDocument()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+221
View File
@@ -0,0 +1,221 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { deleteConfig, listConfigs, readConfig, runAction, writeConfig } from '../../api/engines/config'
import type { ConfigKind, EngineDef } from '../../api/engines/registry'
import { draftFromRole, emptyDraft, payloadFromDraft, type RoleData, type RoleDraft } from '../../api/engines/roles'
import { maskConnectionUrl } from '../../model/connectionUrl'
import { ListState } from '../shared/ListState'
import { NameChips } from '../shared/PolicyChips'
import { useConfirm } from '../shared/useConfirm'
import { RoleEditor } from './RoleEditor'
function ConfigEditor({ client, mount, kind, name, initial, onDone }: {
client: BaoClient
mount: string
kind: ConfigKind
/** Config name for named kinds; undefined for single-endpoint configs. */
name?: string
/** Existing values (null when nothing is configured yet). */
initial: RoleData | null
onDone: () => void
}) {
const qc = useQueryClient()
const confirm = useConfirm()
const [draft, setDraft] = useState<RoleDraft>(() =>
initial ? draftFromRole(kind, name ?? '', initial) : { ...emptyDraft(kind), name: name ?? '' },
)
const [formError, setFormError] = useState<string | null>(null)
const done = () => qc.invalidateQueries({ queryKey: ['engine-config', mount, kind.id] })
const save = useMutation({
mutationFn: (d: RoleDraft) => writeConfig(client, mount, kind, payloadFromDraft(kind, d), kind.named ? d.name.trim() : undefined),
onSuccess: async () => {
await done()
onDone()
},
})
const act = useMutation({
mutationFn: (id: string) => runAction(client, mount, kind.actions!.find((a) => a.id === id)!, name),
onSuccess: done,
})
const remove = useMutation({
mutationFn: () => deleteConfig(client, mount, kind, name),
onSuccess: async () => {
await done()
onDone()
},
})
const shown = kind.shown?.filter((s) => typeof initial?.[s.key] === 'string' && initial[s.key] !== '')
return (
<div>
{shown?.map((s) => (
<label key={s.key}>
{s.label}
<textarea readOnly rows={3} value={String(initial?.[s.key])} />
</label>
))}
<RoleEditor
kind={kind}
noun={kind.named ? 'connection' : kind.label.toLowerCase()}
showName={kind.named}
draft={draft}
pending={save.isPending}
error={formError ?? save.error?.message ?? null}
onChange={setDraft}
onSubmit={() => {
setFormError(null)
try {
payloadFromDraft(kind, draft)
} catch (e) {
setFormError((e as Error).message)
return
}
save.mutate(draft)
}}
onCancel={onDone}
/>
{(initial !== null || !kind.named) &&
kind.actions?.map((a) => (
<button
key={a.id}
type="button"
disabled={act.isPending}
onClick={async () => {
if (await confirm(a.confirm)) act.mutate(a.id)
}}
>
{a.label}
</button>
))}
{kind.deletable && initial !== null && (
<button
type="button"
onClick={async () => {
if (await confirm({ title: `Delete ${kind.named ? `“${name}”` : kind.label.toLowerCase()}?`, message: 'This cannot be undone.', confirmLabel: 'Delete' }))
remove.mutate()
}}
>
Delete
</button>
)}
{act.isSuccess && <p role="status">Done.</p>}
{act.error && <p role="alert">{act.error.message}</p>}
{remove.error && <p role="alert">{remove.error.message}</p>}
</div>
)
}
function SingleConfig({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
const q = useQuery({ queryKey: ['engine-config', mount, kind.id, ''], queryFn: () => readConfig(client, mount, kind) })
if (q.isPending) return <p role="status">Loading…</p>
if (q.error) return <p role="alert">{q.error.message}</p>
// `key` remounts the form with fresh values after a save or action reloads the config.
return (
<ConfigEditor
key={JSON.stringify(q.data)}
client={client}
mount={mount}
kind={kind}
initial={q.data}
onDone={() => void q.refetch()}
/>
)
}
/** One connection in the list: its URL and the roles allowed to use it, read from the connection itself. */
function ConnectionRow({ client, mount, kind, name, onEdit }: {
client: BaoClient
mount: string
kind: ConfigKind
name: string
onEdit: () => void
}) {
const cfg = useQuery({ queryKey: ['engine-config', mount, kind.id, name], queryFn: () => readConfig(client, mount, kind, name) })
const url = cfg.data?.connection_url
const roles = Array.isArray(cfg.data?.allowed_roles) ? (cfg.data.allowed_roles as string[]) : []
return (
<tr>
<td>{name}</td>
<td data-label="Connection URL">
{cfg.isPending ? (
<span className="hint">Loading…</span>
) : cfg.error ? (
<span role="alert">{cfg.error.message}</span>
) : typeof url === 'string' && url ? (
<code>{maskConnectionUrl(url)}</code>
) : (
<span className="hint">None</span>
)}
</td>
<td data-label="Allowed roles">{cfg.data ? <NameChips names={roles} /> : null}</td>
<td>
<button type="button" aria-label={`Edit ${name}`} onClick={onEdit}>
Edit
</button>
</td>
</tr>
)
}
function NamedConfigs({ client, mount, kind }: { client: BaoClient; mount: string; kind: ConfigKind }) {
const [editing, setEditing] = useState<{ name?: string; initial: RoleData | null } | null>(null)
const names = useQuery({ queryKey: ['engine-config', mount, kind.id], queryFn: () => listConfigs(client, mount, kind) })
const open = useMutation({
mutationFn: (name: string) => readConfig(client, mount, kind, name),
onSuccess: (initial, name) => setEditing({ name, initial }),
})
return (
<div>
<ListState query={names} empty={`No ${kind.label.toLowerCase()} yet.`} />
{!!names.data?.length && (
<table aria-label={kind.label}>
<thead>
<tr>
<th>Name</th>
<th>Connection URL</th>
<th>Allowed roles</th>
<th />
</tr>
</thead>
<tbody>
{names.data.map((n) => (
<ConnectionRow key={n} client={client} mount={mount} kind={kind} name={n} onEdit={() => open.mutate(n)} />
))}
</tbody>
</table>
)}
{open.error && <p role="alert">{open.error.message}</p>}
{!editing && (
<button type="button" onClick={() => setEditing({ initial: null })}>
New connection
</button>
)}
{editing && (
<ConfigEditor
key={editing.name ?? 'new'}
client={client}
mount={mount}
kind={kind}
name={editing.name}
initial={editing.initial}
onDone={() => setEditing(null)}
/>
)}
</div>
)
}
export function ConfigPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
return (
<section aria-label="Config">
{engine.configs.map((kind) => (
<div key={kind.id}>
<h3>{kind.label}</h3>
{kind.named ? <NamedConfigs client={client} mount={mount} kind={kind} /> : <SingleConfig client={client} mount={mount} kind={kind} />}
</div>
))}
</section>
)
}
@@ -0,0 +1,144 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } 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 mounts from '../../api/mounts'
import type { Mount } from '../../api/secrets'
import { DeleteMountDialog } from './DeleteMountDialog'
vi.mock('../../api/mounts', async (orig) => ({ ...(await orig<typeof mounts>()), deleteMount: vi.fn(), mountImpact: vi.fn() }))
vi.mock('../shared/useAccessInputs', () => ({ useAccessInputs: vi.fn() }))
import { useAccessInputs } from '../shared/useAccessInputs'
const client = new BaoClient('http://b', 't')
const kv: Mount = { path: 'secret/', type: 'kv', version: '2' }
const db: Mount = { path: 'database/', type: 'database' }
function policies(list: { name: string; hcl: string | null }[], error: Error | null = null) {
vi.mocked(useAccessInputs).mockReturnValue({ data: error ? undefined : { identities: [], policies: list, notes: [] }, error } as never)
}
beforeEach(() => policies([]))
afterEach(() => vi.resetAllMocks())
function setup(mount: Mount) {
const onClose = vi.fn()
const onDeleted = vi.fn()
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(
<QueryClientProvider client={qc}>
<DeleteMountDialog client={client} mount={mount} onClose={onClose} onDeleted={onDeleted} />
</QueryClientProvider>,
)
return { user: userEvent.setup(), onClose, onDeleted, qc }
}
const deleteButton = () => screen.getByRole('button', { name: 'Delete forever' })
test('describes what deleting a KV store destroys', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 4, unknown: [] })
setup(kv)
expect(await screen.findByText(/with all of its versions, will be permanently deleted/)).toHaveTextContent('at least 4 entries at the top level')
expect(screen.getByText('This cannot be undone.')).toBeInTheDocument()
expect(mounts.mountImpact).toHaveBeenCalledWith(client, 'secret/', 'kv')
})
test('describes a dynamic engine, including that leases are revoked', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 1, hasLeases: true, unknown: [] })
setup(db)
const text = await screen.findByText(/engine at/)
expect(text).toHaveTextContent('Database engine at database/ will be permanently deleted, with its 1 role and its configuration.')
expect(text).toHaveTextContent('Every lease it has issued will be revoked')
})
test('does not claim leases are revoked when there are none', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] })
setup(db)
expect(await screen.findByText(/engine at/)).not.toHaveTextContent('lease')
})
test('says what it could not count', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 2, hasLeases: undefined, unknown: ['leases'] })
setup(db)
expect(await screen.findByText('Could not count leases, so there may be more than shown.')).toBeInTheDocument()
})
test('lists policies that refer to the mount and leaves them alone', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
policies([
{ name: 'envbao-user-alice', hcl: 'path "secret/data/team-a/*" { capabilities = ["read"] }' },
{ name: 'unrelated', hcl: 'path "other/x" { capabilities = ["read"] }' },
])
setup(kv)
expect(await screen.findByText(/1 policy grants access under this mount/)).toBeInTheDocument()
expect(screen.getByText('envbao-user-alice')).toBeInTheDocument()
expect(screen.queryByText('unrelated')).not.toBeInTheDocument()
})
test('says when policies could not be checked', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
policies([], new Error('permission denied'))
setup(kv)
expect(await screen.findByText(/Could not check which policies refer to this mount: permission denied/)).toBeInTheDocument()
})
test('Delete stays disabled until the path is typed, and nothing is deleted before then', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
const { user } = setup(kv)
expect(deleteButton()).toBeDisabled()
await user.type(screen.getByLabelText(/Type/), 'secre')
expect(deleteButton()).toBeDisabled()
await user.type(screen.getByLabelText(/Type/), 'x')
expect(deleteButton()).toBeDisabled()
expect(mounts.deleteMount).not.toHaveBeenCalled()
})
test.each(['secret/', 'secret', ' secret/ '])('deleting after typing "%s"', async (typed) => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
vi.mocked(mounts.deleteMount).mockResolvedValue()
const { user, onDeleted } = setup(kv)
await user.type(screen.getByLabelText(/Type/), typed)
await user.click(deleteButton())
expect(mounts.deleteMount).toHaveBeenCalledWith(client, 'secret/')
expect(onDeleted).toHaveBeenCalled()
})
test('a different mount name does not unlock it', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
const { user } = setup(kv)
await user.type(screen.getByLabelText(/Type/), 'secrets')
expect(deleteButton()).toBeDisabled()
})
test('shows the server error and stays open', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
vi.mocked(mounts.deleteMount).mockRejectedValue(new Error('permission denied'))
const { user, onDeleted } = setup(kv)
await user.type(screen.getByLabelText(/Type/), 'secret')
await user.click(deleteButton())
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
expect(onDeleted).not.toHaveBeenCalled()
})
test('cancel closes without deleting', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
const { user, onClose } = setup(kv)
await user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(onClose).toHaveBeenCalled()
expect(mounts.deleteMount).not.toHaveBeenCalled()
})
test('forgets cached data for the deleted mount', async () => {
vi.mocked(mounts.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] })
vi.mocked(mounts.deleteMount).mockResolvedValue()
const { user, qc } = setup(db)
qc.setQueryData(['engine-roles', 'database/', 'roles'], ['ro'])
qc.setQueryData(['engine-roles', 'ssh/', 'roles'], ['keep'])
await user.type(screen.getByLabelText(/Type/), 'database')
await user.click(deleteButton())
await vi.waitFor(() => expect(mounts.deleteMount).toHaveBeenCalled())
await vi.waitFor(() => expect(qc.getQueryData(['engine-roles', 'database/', 'roles'])).toBeUndefined())
expect(qc.getQueryData(['engine-roles', 'ssh/', 'roles'])).toEqual(['keep'])
})
+105
View File
@@ -0,0 +1,105 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useId, useState, type FormEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import { engineFor } from '../../api/engines/registry'
import { deleteMount, mountImpact, type MountImpact } from '../../api/mounts'
import type { Mount } from '../../api/secrets'
import { policiesReferencing } from '../../model/mounts'
import { useAccessInputs } from '../shared/useAccessInputs'
import { NameChips } from '../shared/PolicyChips'
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
function Consequences({ mount, impact }: { mount: Mount; impact: MountImpact }) {
if (impact.kind === 'kv') {
return (
<p>
Every secret stored in <code>{mount.path}</code>, with all of its versions, will be permanently deleted
{impact.topLevelEntries !== undefined && <> (at least {plural(impact.topLevelEntries, 'entry', 'entries')} at the top level)</>}.
</p>
)
}
return (
<p>
The {engineFor(mount.type).label} engine at <code>{mount.path}</code> will be permanently deleted
{impact.roles !== undefined && <>, with its {plural(impact.roles, 'role')} and its configuration</>}.
{impact.hasLeases ? ' Every lease it has issued will be revoked, so credentials already handed out stop working.' : ''}
</p>
)
}
/**
* Deleting a mount destroys its data and revokes its leases, so the button stays disabled until the path is typed.
* Policies that mention the mount are listed, not changed: they are left in place.
*/
export function DeleteMountDialog({ client, mount, onClose, onDeleted }: {
client: BaoClient
mount: Mount
onClose: () => void
onDeleted: () => void
}) {
const qc = useQueryClient()
const inputId = useId()
const [typed, setTyped] = useState('')
const impact = useQuery({
queryKey: ['mount-impact', mount.path],
queryFn: () => mountImpact(client, mount.path, mount.type),
gcTime: 0,
staleTime: 0,
})
const access = useAccessInputs(client)
const referencing = access.data ? policiesReferencing(access.data.policies, mount.path) : []
const confirmed = typed.trim().replace(/\/+$/, '') === mount.path.replace(/\/+$/, '')
const remove = useMutation({
mutationFn: () => deleteMount(client, mount.path),
onSuccess: async () => {
qc.removeQueries({ predicate: (q) => ['kv-list', 'engine-roles', 'engine-config', 'leases', 'mount-impact', 'kv-config'].includes(String(q.queryKey[0])) && q.queryKey[1] === mount.path })
await qc.invalidateQueries({ queryKey: ['mounts'] })
onDeleted()
},
})
function submit(e: FormEvent) {
e.preventDefault()
if (confirmed) remove.mutate()
}
return (
<section role="alertdialog" aria-label={`Delete ${mount.path}`} className="mount-dialog mount-delete">
<h3>Delete {mount.path}?</h3>
{impact.isPending && <p role="status">Checking what is in it…</p>}
{impact.error && <p role="alert">{impact.error.message}</p>}
{impact.data && <Consequences mount={mount} impact={impact.data} />}
{impact.data && impact.data.unknown.length > 0 && (
<p className="hint">Could not count {impact.data.unknown.join(', ')}, so there may be more than shown.</p>
)}
<p>This cannot be undone.</p>
{referencing.length > 0 && (
<>
<p>
{plural(referencing.length, 'policy', 'policies')} grant{referencing.length === 1 ? 's' : ''} access under this mount.
They are not changed, and will point at nothing:
</p>
<NameChips names={referencing} />
</>
)}
{access.error && <p className="hint">Could not check which policies refer to this mount: {access.error.message}</p>}
<form onSubmit={submit} aria-label={`Confirm deleting ${mount.path}`}>
<label htmlFor={inputId}>
Type <code>{mount.path}</code> to confirm
</label>
<input id={inputId} value={typed} onChange={(e) => setTyped(e.target.value)} autoComplete="off" spellCheck={false} />
{remove.error && <p role="alert">{remove.error.message}</p>}
<div className="form-actions">
<button type="submit" disabled={!confirmed || remove.isPending}>
Delete forever
</button>
<button type="button" onClick={onClose}>
Cancel
</button>
</div>
</form>
</section>
)
}
+39
View File
@@ -0,0 +1,39 @@
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { engineFor } from '../../api/engines/registry'
import type { Mount } from '../../api/secrets'
import { ConfigPanel } from './ConfigPanel'
import { LeasesPanel } from './LeasesPanel'
import { RolesPanel } from './RolesPanel'
type Tab = 'roles' | 'config' | 'leases'
/** Roles, Config and Leases for a dynamic secrets engine. */
export function EngineView({ client, mount }: { client: BaoClient; mount: Mount }) {
const engine = engineFor(mount.type)
const [tab, setTab] = useState<Tab>('roles')
const tabs: { id: Tab; label: string }[] = [{ id: 'roles', label: 'Roles' }]
if (engine.configs.length > 0) tabs.push({ id: 'config', label: 'Config' })
tabs.push({ id: 'leases', label: 'Leases' })
const current = tabs.some((t) => t.id === tab) ? tab : 'roles'
return (
<div className="engine-view">
<h2>
{engine.label} · {mount.path}
</h2>
{tabs.length > 1 && (
<div role="tablist" aria-label="Engine" className="tabs">
{tabs.map((t) => (
<button key={t.id} type="button" role="tab" aria-selected={t.id === current} onClick={() => setTab(t.id)}>
{t.label}
</button>
))}
</div>
)}
{current === 'roles' && <RolesPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
{current === 'leases' && <LeasesPanel key={mount.path} client={client} mount={mount.path} />}
{current === 'config' && <ConfigPanel key={mount.path} client={client} mount={mount.path} engine={engine} />}
</div>
)
}
@@ -0,0 +1,91 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao'
import * as creds from '../../api/engines/creds'
import * as leases from '../../api/engines/leases'
import { ENGINES } from '../../api/engines/registry'
import { GenerateCreds } from './GenerateCreds'
vi.mock('../../api/engines/creds')
vi.mock('../../api/engines/leases')
const client = new BaoClient('http://b', 't')
afterEach(() => vi.resetAllMocks())
function setup(type: 'database' | 'ssh', kindIndex = 0) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const onClose = vi.fn()
render(
<QueryClientProvider client={qc}>
<GenerateCreds client={client} mount={`${type}/`} role="ro" kinds={ENGINES[type].roleKinds[kindIndex].creds} onClose={onClose} />
</QueryClientProvider>,
)
return { qc, onClose, user: userEvent.setup() }
}
const issued = { leaseId: 'database/creds/ro/abc', leaseDuration: 3600, renewable: true, data: { username: 'v-ro-1', password: 'hunter2' }, warnings: [] }
test('shows issued credentials once, and keeps them out of every cache', async () => {
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
const { qc, onClose, user } = setup('database')
await user.click(screen.getByRole('button', { name: 'Generate' }))
const dialog = await screen.findByRole('dialog', { name: 'Credentials for ro' })
expect(dialog).toHaveTextContent('v-ro-1')
expect(dialog).toHaveTextContent('hunter2')
expect(dialog).toHaveTextContent('valid for 3600s')
expect(JSON.stringify(qc.getQueryCache().getAll().map((q) => q.state.data))).not.toContain('hunter2')
await user.click(screen.getByRole('button', { name: 'Done' }))
expect(onClose).toHaveBeenCalled()
expect(qc.getMutationCache().getAll()).toHaveLength(0)
})
test('a role that takes no input offers just Generate, with no raw JSON box', () => {
setup('database')
expect(screen.getByRole('form', { name: 'Generate credentials for ro' })).toBeInTheDocument()
expect(screen.queryByLabelText(/JSON/)).not.toBeInTheDocument()
})
test('revokes the lease on request', async () => {
vi.mocked(creds.generateCreds).mockResolvedValue(issued)
vi.mocked(leases.revokeLease).mockResolvedValue()
const { user } = setup('database')
await user.click(screen.getByRole('button', { name: 'Generate' }))
await user.click(await screen.findByRole('button', { name: 'Revoke now' }))
expect(leases.revokeLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
expect(await screen.findByRole('status')).toHaveTextContent('Lease revoked.')
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
})
test('credentials without a lease cannot be revoked', async () => {
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', leaseDuration: 0 })
const { user } = setup('database')
await user.click(screen.getByRole('button', { name: 'Generate' }))
expect(await screen.findByText(/No lease/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Revoke now' })).not.toBeInTheDocument()
})
test('ssh: choose between signing and OTP, and validate inputs before calling OpenBao', async () => {
vi.mocked(creds.generateCreds).mockResolvedValue({ ...issued, leaseId: '', data: { signed_key: 'ssh-ed25519-cert-v01@openssh.com AAAA' } })
const { user } = setup('ssh')
// sign is first; the public key is required
await user.type(screen.getByLabelText(/^Public key/), ' ')
await user.click(screen.getByRole('button', { name: 'Generate' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Public key is required.')
expect(creds.generateCreds).not.toHaveBeenCalled()
await user.selectOptions(screen.getByLabelText('Action'), 'otp')
await user.type(screen.getByLabelText('Target IP'), '10.0.0.5')
await user.click(screen.getByRole('button', { name: 'Generate' }))
expect(creds.generateCreds).toHaveBeenCalledWith(client, 'ssh/', ENGINES.ssh.roleKinds[0].creds[1], 'ro', { ip: '10.0.0.5' })
})
test('shows why generating failed', async () => {
vi.mocked(creds.generateCreds).mockRejectedValue(new Error('permission denied'))
const { user } = setup('database')
await user.click(screen.getByRole('button', { name: 'Generate' }))
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+158
View File
@@ -0,0 +1,158 @@
import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { generateCreds, type Credentials } from '../../api/engines/creds'
import { revokeLease } from '../../api/engines/leases'
import type { CredKind } from '../../api/engines/registry'
import { emptyDraft, payloadFromDraft, type RoleDraft } from '../../api/engines/roles'
import { RoleEditor } from './RoleEditor'
const show = (v: unknown) => (typeof v === 'string' ? v : JSON.stringify(v, null, 2))
function CopyButton({ text, label }: { text: string; label: string }) {
return (
<button type="button" aria-label={`Copy ${label}`} onClick={() => void navigator.clipboard?.writeText(text).catch(() => {})}>
Copy
</button>
)
}
/**
* Asks OpenBao for credentials and shows them exactly once. The result lives only in this component's mutation
* (gcTime 0, reset on dismiss): it is never a query, so it is never cached, persisted or put in the URL.
*/
export function GenerateCreds({
client,
mount,
role,
kinds,
onClose,
}: {
client: BaoClient
mount: string
role: string
kinds: CredKind[]
onClose: () => void
}) {
const [kindId, setKindId] = useState(kinds[0].id)
const kind = kinds.find((k) => k.id === kindId) ?? kinds[0]
const [draft, setDraft] = useState<RoleDraft>(() => emptyDraft({ fields: kind.inputs }))
const [formError, setFormError] = useState<string | null>(null)
const generate = useMutation({
gcTime: 0,
mutationFn: (body: Record<string, unknown>) => generateCreds(client, mount, kind, role, body),
})
const revoke = useMutation({ gcTime: 0, mutationFn: (leaseId: string) => revokeLease(client, leaseId) })
const close = () => {
generate.reset()
revoke.reset()
onClose()
}
if (generate.data) return <Issued creds={generate.data} role={role} revoke={revoke} onRevoke={() => revoke.mutate(generate.data.leaseId)} onDone={close} />
return (
<div className="creds">
{kinds.length > 1 && (
<label>
Action
<select
value={kind.id}
onChange={(e) => {
const next = kinds.find((k) => k.id === e.target.value) ?? kinds[0]
setKindId(next.id)
setDraft(emptyDraft({ fields: next.inputs }))
setFormError(null)
}}
>
{kinds.map((k) => (
<option key={k.id} value={k.id}>
{k.label}
</option>
))}
</select>
</label>
)}
<RoleEditor
key={kind.id}
kind={{ fields: kind.inputs }}
noun={`${kind.label.toLowerCase()} for ${role}`}
title={`${kind.label} for ${role}`}
rawJson={false}
showName={false}
submitLabel="Generate"
draft={draft}
pending={generate.isPending}
error={formError ?? generate.error?.message ?? null}
onChange={setDraft}
onSubmit={() => {
setFormError(null)
try {
generate.mutate(payloadFromDraft({ fields: kind.inputs }, draft))
} catch (e) {
setFormError((e as Error).message)
}
}}
onCancel={close}
/>
</div>
)
}
function Issued({
creds,
role,
revoke,
onRevoke,
onDone,
}: {
creds: Credentials
role: string
revoke: { isPending: boolean; isSuccess: boolean; error: Error | null }
onRevoke: () => void
onDone: () => void
}) {
return (
<section role="dialog" aria-label={`Credentials for ${role}`} className="creds-issued">
<h3>Credentials for {role}</h3>
<p className="hint">Copy these now. They are not stored and cannot be shown again.</p>
<dl>
{Object.entries(creds.data).map(([k, v]) => (
<div key={k}>
<dt>{k}</dt>
<dd>
<code>{show(v)}</code> <CopyButton text={show(v)} label={k} />
</dd>
</div>
))}
</dl>
{creds.leaseId ? (
<p>
Lease <code>{creds.leaseId}</code>
{creds.leaseDuration > 0 && ` · valid for ${creds.leaseDuration}s`}
</p>
) : (
<p className="hint">No lease: these credentials are not revoked when they expire.</p>
)}
{creds.warnings.map((w) => (
<p key={w} className="hint">
{w}
</p>
))}
{revoke.error && <p role="alert">{revoke.error.message}</p>}
{revoke.isSuccess && <p role="status">Lease revoked.</p>}
<div className="form-actions">
{creds.leaseId && !revoke.isSuccess && (
<button type="button" onClick={onRevoke} disabled={revoke.isPending}>
Revoke now
</button>
)}
<button type="button" onClick={onDone}>
Done
</button>
</div>
</section>
)
}
+99
View File
@@ -0,0 +1,99 @@
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 leases from '../../api/engines/leases'
import { LeasesPanel } from './LeasesPanel'
vi.mock('../../api/engines/leases')
const client = new BaoClient('http://b', 't')
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<LeasesPanel client={client} mount="database/" />
</QueryClientProvider>,
)
return userEvent.setup()
}
beforeEach(() => {
vi.mocked(leases.listLeases).mockImplementation(async (_c, prefix) =>
prefix === 'database/'
? [{ name: 'creds/', path: 'database/creds/', isFolder: true }]
: prefix === 'database/creds/'
? [{ name: 'ro/', path: 'database/creds/ro/', isFolder: true }]
: [{ name: 'abc', path: 'database/creds/ro/abc', isFolder: false }],
)
vi.mocked(leases.lookupLease).mockResolvedValue({
id: 'database/creds/ro/abc',
issueTime: '2026-01-01T00:00:00Z',
expireTime: '2026-01-01T01:00:00Z',
lastRenewal: null,
renewable: true,
ttl: 3000,
})
})
afterEach(() => vi.resetAllMocks())
async function openLease(user: ReturnType<typeof userEvent.setup>) {
await user.click(await screen.findByRole('button', { name: /creds\// }))
await user.click(await screen.findByRole('button', { name: /ro\// }))
}
test('browses folders down to a lease and shows its details', async () => {
const user = setup()
await openLease(user)
await user.click(await screen.findByRole('button', { name: 'Details abc' }))
const details = await screen.findByLabelText('Lease abc')
expect(within(details).getByText('3000s')).toBeInTheDocument()
expect(leases.lookupLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
})
test('renews a renewable lease', async () => {
vi.mocked(leases.renewLease).mockResolvedValue(3600)
const user = setup()
await openLease(user)
await user.click(await screen.findByRole('button', { name: 'Details abc' }))
await user.click(await screen.findByRole('button', { name: 'Renew' }))
expect(leases.renewLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
})
test('revokes one lease only after confirmation', async () => {
vi.mocked(leases.revokeLease).mockResolvedValue()
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false)
const user = setup()
await openLease(user)
await user.click(await screen.findByRole('button', { name: 'Revoke abc' }))
expect(leases.revokeLease).not.toHaveBeenCalled()
confirm.mockReturnValue(true)
await user.click(screen.getByRole('button', { name: 'Revoke abc' }))
expect(leases.revokeLease).toHaveBeenCalledWith(client, 'database/creds/ro/abc')
})
test('revoke-all is offered below the mount root and names the prefix', async () => {
vi.mocked(leases.revokePrefix).mockResolvedValue()
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(true)
const user = setup()
await screen.findByRole('button', { name: /creds\// })
expect(screen.queryByRole('button', { name: /Revoke all/ })).not.toBeInTheDocument()
await openLease(user)
await user.click(await screen.findByRole('button', { name: 'Revoke all under this prefix' }))
expect(confirm.mock.calls[0][0]).toContain('database/creds/ro/')
expect(leases.revokePrefix).toHaveBeenCalledWith(client, 'database/creds/ro/')
})
test('says so when there are no leases, and why listing failed', async () => {
vi.mocked(leases.listLeases).mockResolvedValueOnce([])
setup()
expect(await screen.findByText('No leases under database/.')).toBeInTheDocument()
})
test('shows the error when listing is not permitted', async () => {
vi.mocked(leases.listLeases).mockRejectedValue(new Error('permission denied'))
setup()
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
})
+134
View File
@@ -0,0 +1,134 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { listLeases, lookupLease, renewLease, revokeLease, revokePrefix } from '../../api/engines/leases'
import { ListState } from '../shared/ListState'
import { useConfirm } from '../shared/useConfirm'
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : 'never')
function LeaseRow({ client, id, name, onChanged }: { client: BaoClient; id: string; name: string; onChanged: () => void }) {
const confirm = useConfirm()
const [open, setOpen] = useState(false)
const info = useQuery({ queryKey: ['lease', id], queryFn: () => lookupLease(client, id), enabled: open, retry: false })
const renew = useMutation({
mutationFn: () => renewLease(client, id),
onSuccess: () => info.refetch(),
})
const revoke = useMutation({ mutationFn: () => revokeLease(client, id), onSuccess: onChanged })
return (
<li className="lease-row">
<span>{name}</span>
<button type="button" aria-expanded={open} aria-label={`Details ${name}`} onClick={() => setOpen(!open)}>
Details
</button>
<button
type="button"
aria-label={`Revoke ${name}`}
onClick={async () => {
if (await confirm({ title: 'Revoke this lease?', message: 'The credentials it issued stop working immediately.', confirmLabel: 'Revoke' }))
revoke.mutate()
}}
>
Revoke
</button>
{open && info.isPending && <p role="status">Loading…</p>}
{open && info.error && <p role="alert">{info.error.message}</p>}
{open && info.data && (
<dl aria-label={`Lease ${name}`}>
<dt>Issued</dt>
<dd>{when(info.data.issueTime)}</dd>
<dt>Expires</dt>
<dd>{when(info.data.expireTime)}</dd>
<dt>Remaining</dt>
<dd>{info.data.ttl}s</dd>
{info.data.lastRenewal && (
<>
<dt>Last renewed</dt>
<dd>{when(info.data.lastRenewal)}</dd>
</>
)}
{info.data.renewable && (
<dd>
<button type="button" onClick={() => renew.mutate()} disabled={renew.isPending}>
Renew
</button>
</dd>
)}
</dl>
)}
{renew.error && <p role="alert">{renew.error.message}</p>}
{revoke.error && <p role="alert">{revoke.error.message}</p>}
</li>
)
}
/** Browse and revoke the leases issued by a dynamic engine mount. */
export function LeasesPanel({ client, mount }: { client: BaoClient; mount: string }) {
const qc = useQueryClient()
const confirm = useConfirm()
const [prefix, setPrefix] = useState(mount)
const key = ['leases', mount, prefix]
const entries = useQuery({ queryKey: key, queryFn: () => listLeases(client, prefix), retry: false })
const refresh = () => qc.invalidateQueries({ queryKey: ['leases', mount] })
const revokeAll = useMutation({
mutationFn: () => revokePrefix(client, prefix),
onSuccess: refresh,
})
const crumbs = prefix.slice(mount.length).split('/').filter(Boolean)
const atRoot = prefix === mount
return (
<section aria-label="Leases">
<nav aria-label="Lease path" className="crumbs">
<button type="button" onClick={() => setPrefix(mount)}>
{mount}
</button>
{crumbs.map((c, i) => (
<button key={i} type="button" onClick={() => setPrefix(mount + crumbs.slice(0, i + 1).join('/') + '/')}>
{c}/
</button>
))}
</nav>
<ListState query={entries} empty={`No leases under ${prefix}.`} />
{!!entries.data?.length && (
<ul className="entries" aria-label={`Leases under ${prefix}`}>
{entries.data.map((e) =>
e.isFolder ? (
<li key={e.path}>
<button type="button" className="entry-folder" onClick={() => setPrefix(e.path)}>
{e.name}
<span aria-hidden="true">›</span>
</button>
</li>
) : (
<LeaseRow key={e.path} client={client} id={e.path} name={e.name} onChanged={refresh} />
),
)}
</ul>
)}
{!atRoot && (
<button
type="button"
onClick={async () => {
if (
await confirm({
title: `Revoke every lease under ${prefix}?`,
message: 'All credentials issued under this prefix stop working immediately. This cannot be undone.',
confirmLabel: 'Revoke all',
})
)
revokeAll.mutate()
}}
disabled={revokeAll.isPending}
>
Revoke all under this prefix
</button>
)}
{revokeAll.error && <p role="alert">{revokeAll.error.message}</p>}
</section>
)
}
+155
View File
@@ -0,0 +1,155 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao'
import { MOUNT_TYPES } from '../../api/engines/registry'
import * as mounts from '../../api/mounts'
import type { Mount } from '../../api/secrets'
import { MountDialog } from './MountDialog'
vi.mock('../../api/mounts', async (orig) => ({
...(await orig<typeof mounts>()),
createMount: vi.fn(),
tuneMount: vi.fn(),
readKvConfig: vi.fn(),
}))
const client = new BaoClient('http://b', 't')
const kv = MOUNT_TYPES[0]
const database = MOUNT_TYPES[1]
afterEach(() => vi.resetAllMocks())
function setup(props: { mount?: Mount; existing?: string[] } = {}) {
const onClose = vi.fn()
const onDone = vi.fn()
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<MountDialog client={client} existing={props.existing ?? ['secret/']} mount={props.mount} onClose={onClose} onDone={onDone} />
</QueryClientProvider>,
)
return { user: userEvent.setup(), onClose, onDone }
}
test('creates a KV v2 store with its settings', async () => {
vi.mocked(mounts.createMount).mockResolvedValue()
const { user, onDone } = setup()
await user.type(screen.getByLabelText('Path'), 'scratch')
await user.type(screen.getByLabelText('Description'), 'throwaway')
await user.type(screen.getByLabelText(/^Max versions/), '5')
await user.click(screen.getByLabelText(/Require check-and-set/))
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(mounts.createMount).toHaveBeenCalledWith(client, 'scratch', kv, {
description: 'throwaway',
max_versions: '5',
cas_required: true,
})
expect(onDone).toHaveBeenCalledWith('scratch/')
})
test('each type offers its own settings, and keeps the path you typed', async () => {
const { user } = setup()
expect(screen.queryByLabelText(/Default lease TTL/)).not.toBeInTheDocument()
await user.type(screen.getByLabelText('Path'), 'dbs')
await user.selectOptions(screen.getByLabelText('Type'), 'database')
expect(screen.getByLabelText('Path')).toHaveValue('dbs')
expect(screen.getByLabelText(/Default lease TTL/)).toBeInTheDocument()
expect(screen.queryByLabelText(/Max versions/)).not.toBeInTheDocument()
})
test('creates a dynamic engine with lease TTLs', async () => {
vi.mocked(mounts.createMount).mockResolvedValue()
const { user, onDone } = setup()
await user.selectOptions(screen.getByLabelText('Type'), 'database')
await user.type(screen.getByLabelText('Path'), 'team/db')
await user.type(screen.getByLabelText(/Default lease TTL/), '1h')
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(mounts.createMount).toHaveBeenCalledWith(client, 'team/db', database, { default_lease_ttl: '1h' })
expect(onDone).toHaveBeenCalledWith('team/db/')
})
test.each([
['secret', /already a secrets engine/],
['sys', /reserved/],
['Has Caps', /lowercase/],
['secret/inner', /inside the existing mount/],
])('refuses the path "%s" without calling OpenBao', async (path, message) => {
const { user } = setup()
await user.type(screen.getByLabelText('Path'), path)
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(await screen.findByRole('alert')).toHaveTextContent(message)
expect(mounts.createMount).not.toHaveBeenCalled()
})
test('shows the server error and stays open', async () => {
vi.mocked(mounts.createMount).mockRejectedValue(new Error('plugin not found in the catalog: aws'))
const { user, onDone } = setup()
await user.selectOptions(screen.getByLabelText('Type'), 'aws')
expect(screen.getByText(/Not every OpenBao build includes the AWS engine/)).toBeInTheDocument()
await user.type(screen.getByLabelText('Path'), 'aws')
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(await screen.findByRole('alert')).toHaveTextContent('plugin not found in the catalog')
expect(onDone).not.toHaveBeenCalled()
})
test('a half-finished create says the mount exists and stays open', async () => {
vi.mocked(mounts.createMount).mockRejectedValue(new mounts.PartialMountError('scratch/ was mounted, but saving its KV settings failed: nope'))
const { user, onDone } = setup()
await user.type(screen.getByLabelText('Path'), 'scratch')
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(await screen.findByRole('alert')).toHaveTextContent('scratch/ was mounted, but saving its KV settings failed')
expect(onDone).not.toHaveBeenCalled()
})
test('settings of a dynamic mount are prefilled from what is set on it, and saved with a blank TTL reset', async () => {
vi.mocked(mounts.tuneMount).mockResolvedValue()
const mount: Mount = { path: 'database/', type: 'database', description: 'main db', defaultLeaseTtl: 3600, maxLeaseTtl: 0 }
const { user, onDone } = setup({ mount })
expect(screen.getByLabelText('Description')).toHaveValue('main db')
expect(screen.getByLabelText(/Default lease TTL/)).toHaveValue('3600s')
expect(screen.getByLabelText(/Max lease TTL/)).toHaveValue('') // 0 means "system default", not a value to save back
expect(screen.queryByLabelText('Path')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Type')).not.toBeInTheDocument()
await user.clear(screen.getByLabelText('Description'))
await user.type(screen.getByLabelText('Description'), 'renamed')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(mounts.tuneMount).toHaveBeenCalledWith(client, 'database/', database, { description: 'renamed', default_lease_ttl: '3600s' })
expect(onDone).toHaveBeenCalledWith('database/')
})
test('settings of a KV mount load the KV configuration first', async () => {
vi.mocked(mounts.readKvConfig).mockResolvedValue({ max_versions: 3, cas_required: true, delete_version_after: '0s' })
vi.mocked(mounts.tuneMount).mockResolvedValue()
const { user } = setup({ mount: { path: 'secret/', type: 'kv', version: '2', description: 'kv' } })
expect(await screen.findByLabelText(/^Max versions/)).toHaveValue('3')
expect(screen.getByLabelText(/Require check-and-set/)).toBeChecked()
await user.clear(screen.getByLabelText(/^Max versions/))
await user.type(screen.getByLabelText(/^Max versions/), '10')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(mounts.tuneMount).toHaveBeenCalledWith(client, 'secret/', kv, {
description: 'kv',
max_versions: '10',
cas_required: true,
delete_version_after: '0s',
})
})
test('says so when the KV configuration cannot be read, instead of showing a blank form', async () => {
vi.mocked(mounts.readKvConfig).mockRejectedValue(new Error('permission denied'))
setup({ mount: { path: 'secret/', type: 'kv', version: '2' } })
expect(await screen.findByRole('alert')).toHaveTextContent('permission denied')
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
})
test('engines the UI cannot manage have no settings form', () => {
setup({ mount: { path: 'pki/', type: 'pki' } })
expect(screen.getByText(/can’t change pki engines/)).toBeInTheDocument()
})
test('cancel closes without saving', async () => {
const { user, onClose } = setup()
await user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(onClose).toHaveBeenCalled()
expect(mounts.createMount).not.toHaveBeenCalled()
})
+169
View File
@@ -0,0 +1,169 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import { MOUNT_TYPES, mountTypeFor, type MountType } from '../../api/engines/registry'
import { draftFromRole, emptyDraft, payloadFromDraft, type RoleDraft, type Schema } from '../../api/engines/roles'
import { createMount, PartialMountError, readKvConfig, tuneMount } from '../../api/mounts'
import type { Mount } from '../../api/secrets'
import { validateMountPath } from '../../model/mounts'
import { RoleEditor } from './RoleEditor'
const schemaOf = (t: MountType): Schema => ({ fields: [...t.fields, ...t.configFields] })
function CreateMount({ client, existing, onClose, onDone }: { client: BaoClient; existing: string[]; onClose: () => void; onDone: (path: string) => void }) {
const qc = useQueryClient()
const [type, setType] = useState<MountType>(MOUNT_TYPES[0])
const [draft, setDraft] = useState<RoleDraft>(() => emptyDraft(schemaOf(MOUNT_TYPES[0])))
const [formError, setFormError] = useState<string | null>(null)
const create = useMutation({
mutationFn: async () => {
const path = draft.name.trim().replace(/\/+$/, '')
try {
await createMount(client, path, type, payloadFromDraft(schemaOf(type), draft))
} finally {
// Even a half-finished create leaves a mount behind, so always refresh the list.
await qc.invalidateQueries({ queryKey: ['mounts'] })
}
return `${path}/`
},
onSuccess: (path) => onDone(path),
})
function submit() {
setFormError(null)
const pathError = validateMountPath(draft.name.trim(), existing)
if (pathError) return setFormError(pathError)
try {
payloadFromDraft(schemaOf(type), draft)
} catch (e) {
return setFormError((e as Error).message)
}
create.mutate()
}
return (
<section aria-label="New secrets engine" className="mount-dialog">
<label>
Type
<select
value={type.type}
onChange={(e) => {
const next = MOUNT_TYPES.find((t) => t.type === e.target.value) ?? MOUNT_TYPES[0]
setType(next)
// Keep what was typed in the path; the other fields differ per type.
setDraft({ ...emptyDraft(schemaOf(next)), name: draft.name })
setFormError(null)
create.reset()
}}
>
{MOUNT_TYPES.map((t) => (
<option key={t.type} value={t.type}>
{t.label}
</option>
))}
</select>
</label>
<RoleEditor
key={type.type}
kind={schemaOf(type)}
noun="secrets engine"
nameLabel="Path"
submitLabel="Create"
draft={draft}
pending={create.isPending}
error={formError ?? (create.error instanceof PartialMountError ? create.error.message : create.error?.message) ?? null}
onChange={setDraft}
onSubmit={submit}
onCancel={onClose}
/>
{type.type === 'aws' && (
<p className="hint">Not every OpenBao build includes the AWS engine. If it is missing, OpenBao says the plugin was not found in the catalog.</p>
)}
</section>
)
}
function EditForm({ client, mount, type, initial, onClose, onDone }: {
client: BaoClient
mount: Mount
type: MountType
initial: Record<string, unknown>
onClose: () => void
onDone: (path: string) => void
}) {
const qc = useQueryClient()
const schema = schemaOf(type)
const [draft, setDraft] = useState<RoleDraft>(() => draftFromRole(schema, mount.path, initial))
const [formError, setFormError] = useState<string | null>(null)
const save = useMutation({
mutationFn: async () => {
await tuneMount(client, mount.path, type, payloadFromDraft(schema, draft))
await qc.invalidateQueries({ queryKey: ['mounts'] })
},
onSuccess: () => onDone(mount.path),
})
return (
<RoleEditor
kind={schema}
noun={`${mount.path} settings`}
showName={false}
draft={draft}
pending={save.isPending}
error={formError ?? save.error?.message ?? null}
onChange={setDraft}
onSubmit={() => {
setFormError(null)
try {
payloadFromDraft(schema, draft)
} catch (e) {
return setFormError((e as Error).message)
}
save.mutate()
}}
onCancel={onClose}
/>
)
}
function EditMount({ client, mount, onClose, onDone }: { client: BaoClient; mount: Mount; onClose: () => void; onDone: (path: string) => void }) {
const type = mountTypeFor(mount)
// KV v2 settings live on the engine, not in sys/mounts, so they are read separately.
const kvConfig = useQuery({
queryKey: ['kv-config', mount.path],
queryFn: () => readKvConfig(client, mount.path),
enabled: type !== null && type.configFields.length > 0,
// Never reuse an earlier read: a stale value would be written back as if it were current.
gcTime: 0,
staleTime: 0,
})
if (!type) return <p className="hint">The UI can’t change {mount.type} engines.</p>
if (type.configFields.length > 0 && kvConfig.isPending) return <p role="status">Loading…</p>
if (kvConfig.error) return <p role="alert">{kvConfig.error.message}</p>
return (
<EditForm
client={client}
mount={mount}
type={type}
initial={{
description: mount.description,
default_lease_ttl: mount.defaultLeaseTtl,
max_lease_ttl: mount.maxLeaseTtl,
...kvConfig.data,
}}
onClose={onClose}
onDone={onDone}
/>
)
}
/** Create a secrets engine mount, or change the settings of an existing one. Path and type can't be changed. */
export function MountDialog(props: { client: BaoClient; existing: string[]; mount?: Mount; onClose: () => void; onDone: (path: string) => void }) {
return props.mount ? (
<section aria-label={`Settings for ${props.mount.path}`} className="mount-dialog">
<EditMount client={props.client} mount={props.mount} onClose={props.onClose} onDone={props.onDone} />
</section>
) : (
<CreateMount client={props.client} existing={props.existing} onClose={props.onClose} onDone={props.onDone} />
)
}
+85
View File
@@ -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<Row[]>([{ key: '', value: '' }])
const [formError, setFormError] = useState<string | null>(null)
const create = useMutation({
mutationFn: async () => {
const path = prefix + name.trim()
const data: Record<string, string> = {}
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<Row>) => 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 (
<section aria-label="New secret" className="mount-dialog">
<form aria-label="New secret form" onSubmit={submit}>
<label>
Name
<span className="hint"> in {mount}{prefix}</span>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="expo" autoComplete="off" />
</label>
<div className="kv-rows">
{rows.map((r, i) => (
<div className="kv-row" key={i}>
<input aria-label={`Key ${i + 1}`} placeholder="key" value={r.key} autoComplete="off" onChange={(e) => setRow(i, { key: e.target.value })} />
<input aria-label={`Value ${i + 1}`} type="password" placeholder="value" value={r.value} autoComplete="new-password" onChange={(e) => setRow(i, { value: e.target.value })} />
<button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((_, j) => j !== i))}>
Remove
</button>
</div>
))}
<div>
<button type="button" onClick={() => setRows([...rows, { key: '', value: '' }])}>
Add key
</button>
</div>
</div>
<p className="hint">Values are write-only: they are never shown again, and an existing secret is never overwritten.</p>
{(formError ?? create.error) && <p role="alert">{formError ?? create.error?.message}</p>}
<button type="submit" disabled={create.isPending}>
{create.isPending ? 'Saving…' : 'Create'}
</button>
<button type="button" onClick={onClose}>
Cancel
</button>
</form>
</section>
)
}
@@ -0,0 +1,98 @@
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 { ENGINES } from '../../api/engines/registry'
import * as grants from '../../api/grants'
import * as ids from '../../api/identities'
import * as secrets from '../../api/secrets'
import * as tokens from '../../api/tokens'
import { RoleAccessPanel } from './RoleAccessPanel'
vi.mock('../../api/grants')
vi.mock('../../api/identities')
vi.mock('../../api/secrets', async (orig) => ({ ...(await orig<typeof secrets>()), readPolicyHcl: vi.fn() }))
vi.mock('../../api/tokens')
const client = new BaoClient('http://b', 't')
const kind = ENGINES.database.roleKinds[0]
beforeEach(() => {
vi.mocked(ids.listUsers).mockResolvedValue([
{ name: 'alice', policies: ['db-ro'], ttl: 0 },
{ name: 'bob', policies: ['other'], ttl: 0 },
])
vi.mocked(ids.listEntities).mockResolvedValue([])
vi.mocked(ids.listGroups).mockResolvedValue([])
vi.mocked(tokens.listTokens).mockResolvedValue([])
vi.mocked(ids.listPolicyNames).mockResolvedValue(['db-ro', 'other'])
vi.mocked(secrets.readPolicyHcl).mockImplementation(async (_c, n) =>
n === 'db-ro' ? 'path "database/creds/*" { capabilities = ["read"] }' : 'path "secret/data/x" { capabilities = ["read"] }',
)
})
afterEach(() => vi.resetAllMocks())
function setup() {
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<RoleAccessPanel client={client} mount="database/" kind={kind} role="ro" onClose={() => {}} />
</QueryClientProvider>,
)
return userEvent.setup()
}
test('shows who can generate credentials from the role', async () => {
setup()
const table = await screen.findByRole('table', { name: 'Who can: Generate credentials' })
const row = within(table).getByText('alice').closest('tr')!
expect(within(row).getByText('db-ro')).toBeInTheDocument()
expect(within(row).getByText('read')).toBeInTheDocument()
expect(within(table).queryByText('bob')).not.toBeInTheDocument()
expect(screen.getByText('No identity can manage this role.')).toBeInTheDocument()
})
test('grants generate on one role', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.selectOptions(screen.getByLabelText('Who'), 'bob')
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'bob' }, [
{ path: 'database/creds/ro', capabilities: ['read'] },
{ path: 'database/roles/ro', capabilities: [] },
])
expect(await screen.findByRole('status')).toHaveTextContent('Granted generate credentials on database/roles/ro to user “bob”.')
})
test('can grant every role, and requires some access', async () => {
vi.mocked(grants.grantAccess).mockResolvedValue()
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.click(screen.getByLabelText(/Every role in/))
await user.click(screen.getByLabelText(/Manage role/))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(grants.grantAccess).toHaveBeenCalledWith(client, { kind: 'user', name: 'alice' }, [
{ path: 'database/creds/*', capabilities: ['read'] },
{ path: 'database/roles/*', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('refuses to grant nothing', async () => {
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
const form = screen.getByRole('form', { name: 'Grant access to this role' })
await user.click(within(form).getByLabelText(/Generate credentials/))
await user.click(within(form).getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Select at least one kind of access.')
expect(grants.grantAccess).not.toHaveBeenCalled()
})
test('shows why a grant failed', async () => {
vi.mocked(grants.grantAccess).mockRejectedValue(new Error('Policy was edited outside EnvBao'))
const user = setup()
await user.click(await screen.findByRole('button', { name: 'Grant access' }))
await user.click(screen.getByRole('button', { name: 'Grant' }))
expect(await screen.findByRole('alert')).toHaveTextContent('edited outside EnvBao')
})
+192
View File
@@ -0,0 +1,192 @@
import { useMutation } from '@tanstack/react-query'
import { useState, type FormEvent, type KeyboardEvent } from 'react'
import type { BaoClient } from '../../api/bao'
import type { RoleKind } from '../../api/engines/registry'
import { grantAccess } from '../../api/grants'
import type { Identity } from '../../model/graph'
import { dynamicGrantRules, validateGrantPath, type DynamicAccess } from '../../model/managed'
import { DynamicAccessPicker } from '../shared/DynamicAccessPicker'
import { useAccessInputs } from '../shared/useAccessInputs'
import { useRefreshAccess } from '../shared/useRefreshAccess'
import { Entries } from './AccessPanel'
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
function GrantRole({ client, mount, kind, role, identities, onClose, onGranted }: {
client: BaoClient
mount: string
kind: RoleKind
role: string
identities: Identity[]
onClose: () => void
onGranted: (message: string) => void
}) {
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 [all, setAll] = useState(false)
const [access, setAccess] = useState<DynamicAccess[]>(['generate'])
const [error, setError] = useState<string | null>(null)
const target = people[who]
const granted = all ? '*' : role
const grant = useMutation({
mutationFn: () =>
grantAccess(client, { kind: target.kind as 'user' | 'entity' | 'group', name: target.name }, dynamicGrantRules(kind, mount, granted, access)),
onSuccess: async () => {
await refresh()
const where = all ? `every role in ${mount}${kind.path}` : `${mount}${kind.path}/${role}`
onGranted(`Granted ${access.map((a) => (a === 'generate' ? 'generate credentials' : 'manage role')).join(' and ')} on ${where} to ${target.kind} “${target.name}”.`)
},
})
function submit(e: FormEvent) {
e.preventDefault()
const err = validateGrantPath(`${mount}${kind.path}/${granted}`) ?? (access.length === 0 ? 'Select at least one kind of access.' : 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 role" 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>
<label className="check">
<input type="checkbox" checked={all} onChange={(e) => setAll(e.target.checked)} />
<span>
Every role in <code>{mount + kind.path}</code>
<span className="hint"> including ones added later</span>
</span>
</label>
<DynamicAccessPicker value={access} onChange={setAccess} />
{(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>
)
}
/** Who can generate credentials from, or manage, one role; and a form to grant that to an identity. */
export function RoleAccessPanel({ client, mount, kind, role, onClose }: {
client: BaoClient
mount: string
kind: RoleKind
role: string
onClose: () => void
}) {
const data = useAccessInputs(client)
const [granting, setGranting] = useState(false)
const [granted, setGranted] = useState<string | null>(null)
const credPaths = kind.creds.map((c) => ({ id: c.id, label: c.label, path: mount + c.path(role) }))
const rolePath = `${mount}${kind.path}/${role}`
return (
<section aria-label={`Access to ${role}`} className="secret-detail">
<header>
<div>
<h2>{role}</h2>
<code>{rolePath}</code>
</div>
<div>
{!granting && (
<button
type="button"
disabled={!data.data}
onClick={() => {
setGranted(null)
setGranting(true)
}}
>
Grant access
</button>
)}
<button type="button" onClick={onClose}>
Close
</button>
</div>
</header>
{granted && (
<p role="status" className="note-ok">
{granted}
</p>
)}
{granting && data.data && (
<GrantRole
client={client}
mount={mount}
kind={kind}
role={role}
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 && (
<>
{data.data.notes.map((n) => (
<p key={n} role="alert">
Incomplete: could not read {n}
</p>
))}
{credPaths.map((c) => (
<div key={c.id}>
<h3>{c.label}</h3>
<code>{c.path}</code>
<Entries data={{ ...data.data, notes: [] }} path={c.path} label={`Who can: ${c.label}`} empty="No identity can do this." />
</div>
))}
<h3>Manage role</h3>
<code>{rolePath}</code>
<Entries data={{ ...data.data, notes: [] }} path={rolePath} label="Who can manage this role" empty="No identity can manage this role." />
</>
)}
</section>
)
}
+173
View File
@@ -0,0 +1,173 @@
import { useId, type FormEvent } from 'react'
import type { FieldDef } from '../../api/engines/registry'
import type { RoleDraft, Schema } from '../../api/engines/roles'
function Field({ field, value, onChange }: { field: FieldDef; value: string | boolean; onChange: (v: string | boolean) => void }) {
const helpId = useId()
const help = field.help ? (
<span id={helpId} className="hint">
{field.help}
</span>
) : null
const describedBy = field.help ? helpId : undefined
if (field.type === 'bool') {
return (
// "check" lays the box beside its text; a plain label in a form stacks them.
<label className="check">
<input type="checkbox" checked={value === true} onChange={(e) => onChange(e.target.checked)} aria-describedby={describedBy} />{' '}
{field.label}
</label>
)
}
if (field.type === 'secret') {
const hint = 'Write-only. Leave blank to keep the stored value.'
return (
<label>
{field.label}
{field.multiline ? (
<textarea
value={String(value)}
onChange={(e) => onChange(e.target.value)}
rows={4}
spellCheck={false}
autoComplete="off"
placeholder={hint}
aria-describedby={describedBy}
/>
) : (
<input
type="password"
value={String(value)}
onChange={(e) => onChange(e.target.value)}
required={field.required}
autoComplete="new-password"
placeholder={hint}
aria-describedby={describedBy}
/>
)}
{help}
</label>
)
}
if (field.type === 'select') {
return (
<label>
{field.label}
<select value={String(value)} onChange={(e) => onChange(e.target.value)} required={field.required} aria-describedby={describedBy}>
{field.options?.map((o) => (
<option key={o}>{o}</option>
))}
</select>
{help}
</label>
)
}
if (field.type === 'textarea' || field.type === 'statements') {
return (
<label>
{field.label}
<textarea
value={String(value)}
onChange={(e) => onChange(e.target.value)}
rows={field.type === 'statements' ? 5 : 4}
required={field.required}
spellCheck={false}
aria-describedby={describedBy}
/>
{help}
</label>
)
}
return (
<label>
{field.label}
<input
value={String(value)}
onChange={(e) => onChange(e.target.value)}
required={field.required}
placeholder={field.type === 'ttl' ? 'e.g. 1h (optional)' : field.type === 'list' ? 'comma separated' : undefined}
aria-describedby={describedBy}
/>
{help}
</label>
)
}
export function RoleEditor({
kind,
noun = 'role',
showName = true,
nameLabel,
title: titleOverride,
rawJson = true,
submitLabel = 'Save',
draft,
pending,
error,
onChange,
onSubmit,
onCancel,
}: {
kind: Schema
/** What is being edited, for the form title: "role", "connection", ... */
noun?: string
/** False for single-endpoint configs that have no name. */
showName?: boolean
/** Label for the name field; defaults to "<Noun> name". */
nameLabel?: string
/** Replaces the generated form title. */
title?: string
/** Show a raw JSON box when the schema has no fields (generic engines). False for forms that take no input. */
rawJson?: boolean
submitLabel?: string
draft: RoleDraft
pending: boolean
error: string | null
onChange: (d: RoleDraft) => void
onSubmit: () => void
onCancel: () => void
}) {
const title = titleOverride ?? (draft.isNew ? `New ${noun}` : showName ? `Edit ${draft.name}` : `Edit ${noun}`)
function submit(e: FormEvent) {
e.preventDefault()
onSubmit()
}
return (
<form onSubmit={submit} aria-label={title} className="wide">
<h3>{title}</h3>
{showName && (
<label>
{nameLabel ?? `${noun[0].toUpperCase() + noun.slice(1)} name`}
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => onChange({ ...draft, name: e.target.value })} required />
</label>
)}
{kind.fields.length === 0 ? (
rawJson && (
<label>
Role (JSON)
<textarea value={draft.json} onChange={(e) => onChange({ ...draft, json: e.target.value })} rows={10} spellCheck={false} />
</label>
)
) : (
kind.fields.map((f) => (
<Field
key={f.key}
field={f}
value={draft.values[f.key] ?? ''}
onChange={(v) => onChange({ ...draft, values: { ...draft.values, [f.key]: v } })}
/>
))
)}
{error && <p role="alert">{error}</p>}
<div className="form-actions">
<button type="submit" disabled={pending}>
{submitLabel}
</button>
<button type="button" onClick={onCancel}>
Cancel
</button>
</div>
</form>
)
}
+131
View File
@@ -0,0 +1,131 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } 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 { ENGINES } from '../../api/engines/registry'
import * as roles from '../../api/engines/roles'
import { RolesPanel } from './RolesPanel'
vi.mock('../../api/engines/roles', async (orig) => ({
...(await orig<typeof roles>()),
listRoles: vi.fn(),
readRole: vi.fn(),
writeRole: vi.fn(),
deleteRole: vi.fn(),
}))
const client = new BaoClient('http://b', 't')
function renderPanel(type: keyof typeof ENGINES = 'database') {
return render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<RolesPanel client={client} mount={`${type}/`} engine={ENGINES[type]} />
</QueryClientProvider>,
)
}
beforeEach(() => {
vi.mocked(roles.listRoles).mockResolvedValue(['readonly'])
})
afterEach(() => vi.resetAllMocks())
test('creates a database role from the form', async () => {
vi.mocked(roles.writeRole).mockResolvedValue()
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'New role' }))
await user.type(screen.getByLabelText('Role name'), 'rw')
await user.type(screen.getByLabelText('Database config name'), 'pg')
await user.type(screen.getByLabelText(/^Creation statements/), 'CREATE ROLE "{{{{name}}";')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(roles.writeRole).toHaveBeenCalledWith(
client,
'database/',
ENGINES.database.roleKinds[0],
'rw',
expect.objectContaining({ db_name: 'pg', creation_statements: ['CREATE ROLE "{{name}}";'] }),
)
expect(screen.queryByRole('form')).not.toBeInTheDocument()
})
test('shows validation errors without calling OpenBao', async () => {
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'New role' }))
await user.type(screen.getByLabelText('Role name'), 'rw')
await user.type(screen.getByLabelText('Database config name'), 'pg')
// the statements field is `required` natively, so fill it with whitespace to reach our own check
await user.type(screen.getByLabelText(/^Creation statements/), ' ')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(await screen.findByRole('alert')).toHaveTextContent('Creation statements is required.')
expect(roles.writeRole).not.toHaveBeenCalled()
})
test('edits an existing role, preserving fields the form does not know', async () => {
vi.mocked(roles.readRole).mockResolvedValue({
db_name: 'pg',
creation_statements: ['CREATE ROLE a;'],
default_ttl: 60,
credential_type: 'password',
})
vi.mocked(roles.writeRole).mockResolvedValue()
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Edit readonly' }))
expect(await screen.findByLabelText('Default TTL')).toHaveValue('60s')
expect(screen.getByLabelText('Role name')).toBeDisabled()
await user.clear(screen.getByLabelText('Default TTL'))
await user.type(screen.getByLabelText('Default TTL'), '2h')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(roles.writeRole).toHaveBeenCalledWith(
client,
'database/',
ENGINES.database.roleKinds[0],
'readonly',
expect.objectContaining({ default_ttl: '2h', credential_type: 'password', db_name: 'pg' }),
)
})
test('deletes a role after confirmation', async () => {
vi.mocked(roles.deleteRole).mockResolvedValue()
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Delete readonly' }))
expect(window.confirm).toHaveBeenCalled()
expect(roles.deleteRole).toHaveBeenCalledWith(client, 'database/', ENGINES.database.roleKinds[0], 'readonly')
})
test('does not delete when the confirmation is declined', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderPanel()
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'Delete readonly' }))
expect(roles.deleteRole).not.toHaveBeenCalled()
})
test('switches between dynamic and static database roles', async () => {
renderPanel()
const user = userEvent.setup()
await screen.findByRole('table', { name: 'Dynamic roles' })
await user.click(screen.getByRole('tab', { name: 'Static roles' }))
expect(await screen.findByRole('table', { name: 'Static roles' })).toBeInTheDocument()
expect(roles.listRoles).toHaveBeenLastCalledWith(client, 'database/', ENGINES.database.roleKinds[1])
})
test('shows an empty state and the load error', async () => {
vi.mocked(roles.listRoles).mockResolvedValue([])
renderPanel('ssh')
expect(await screen.findByText('No roles yet.')).toBeInTheDocument()
})
test('yes/no settings lay the box beside its text (the "check" label), not stacked above it', async () => {
renderPanel('ssh')
const user = userEvent.setup()
await user.click(await screen.findByRole('button', { name: 'New role' }))
const box = screen.getByLabelText('Allow user certificates')
expect(box.closest('label')).toHaveClass('check')
})
+171
View File
@@ -0,0 +1,171 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import type { BaoClient } from '../../api/bao'
import type { EngineDef } from '../../api/engines/registry'
import {
deleteRole,
draftFromRole,
emptyDraft,
listRoles,
payloadFromDraft,
readRole,
writeRole,
type RoleDraft,
} from '../../api/engines/roles'
import { ListState } from '../shared/ListState'
import { useConfirm } from '../shared/useConfirm'
import { GenerateCreds } from './GenerateCreds'
import { RoleAccessPanel } from './RoleAccessPanel'
import { RoleEditor } from './RoleEditor'
export function RolesPanel({ client, mount, engine }: { client: BaoClient; mount: string; engine: EngineDef }) {
const qc = useQueryClient()
const confirm = useConfirm()
const [kindId, setKindId] = useState(engine.roleKinds[0].id)
const kind = engine.roleKinds.find((k) => k.id === kindId) ?? engine.roleKinds[0]
const [draft, setDraft] = useState<RoleDraft | null>(null)
const [formError, setFormError] = useState<string | null>(null)
const [credsFor, setCredsFor] = useState<string | null>(null)
const [accessFor, setAccessFor] = useState<string | null>(null)
const key = ['engine-roles', mount, kind.id]
const roles = useQuery({ queryKey: key, queryFn: () => listRoles(client, mount, kind) })
const save = useMutation({
mutationFn: (d: RoleDraft) => writeRole(client, mount, kind, d.name.trim(), payloadFromDraft(kind, d)),
onSuccess: () => {
setDraft(null)
return qc.invalidateQueries({ queryKey: key })
},
})
const remove = useMutation({
mutationFn: (name: string) => deleteRole(client, mount, kind, name),
onSuccess: () => qc.invalidateQueries({ queryKey: key }),
})
const edit = useMutation({
mutationFn: (name: string) => readRole(client, mount, kind, name).then((data) => draftFromRole(kind, name, data)),
onSuccess: (d) => {
setFormError(null)
setDraft(d)
},
})
const switchKind = (id: string) => {
setKindId(id)
setDraft(null)
setCredsFor(null)
setAccessFor(null)
save.reset()
}
return (
<section aria-label="Roles">
{engine.roleKinds.length > 1 && (
<div role="tablist" aria-label="Role type" className="tabs">
{engine.roleKinds.map((k) => (
<button key={k.id} type="button" role="tab" aria-selected={k.id === kind.id} onClick={() => switchKind(k.id)}>
{k.label}
</button>
))}
</div>
)}
<ListState query={roles} empty={`No ${kind.label.toLowerCase()} yet.`} />
{!!roles.data?.length && (
<table aria-label={kind.label}>
<thead>
<tr>
<th>Role</th>
<th />
</tr>
</thead>
<tbody>
{roles.data.map((name) => (
<tr key={name}>
<td>{name}</td>
<td>
{kind.creds.length > 0 && (
<button type="button" aria-label={`Generate ${name}`} onClick={() => setCredsFor(name)}>
Generate
</button>
)}
<button type="button" aria-label={`Access ${name}`} onClick={() => setAccessFor(name)}>
Access
</button>
<button type="button" aria-label={`Edit ${name}`} onClick={() => edit.mutate(name)}>
Edit
</button>
<button
type="button"
aria-label={`Delete ${name}`}
onClick={async () => {
if (
await confirm({
title: `Delete role “${name}”?`,
message: 'Credentials already issued from it stay valid until their leases end.',
confirmLabel: 'Delete',
})
)
remove.mutate(name)
}}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{credsFor && (
<GenerateCreds
key={`${kind.id}/${credsFor}`}
client={client}
mount={mount}
role={credsFor}
kinds={kind.creds}
onClose={() => setCredsFor(null)}
/>
)}
{accessFor && (
<RoleAccessPanel key={`${kind.id}/${accessFor}`} client={client} mount={mount} kind={kind} role={accessFor} onClose={() => setAccessFor(null)} />
)}
{remove.error && <p role="alert">{remove.error.message}</p>}
{edit.error && <p role="alert">{edit.error.message}</p>}
{!draft && (
<button
type="button"
onClick={() => {
setFormError(null)
save.reset()
setDraft(emptyDraft(kind))
}}
>
New role
</button>
)}
{draft && (
<RoleEditor
kind={kind}
draft={draft}
pending={save.isPending}
error={formError ?? save.error?.message ?? null}
onChange={setDraft}
onSubmit={() => {
setFormError(null)
try {
payloadFromDraft(kind, draft)
} catch (e) {
setFormError((e as Error).message)
return
}
save.mutate(draft)
}}
onCancel={() => {
setDraft(null)
save.reset()
}}
/>
)}
</section>
)
}
+180 -2
View File
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { BaoClient } from '../../api/bao' import { BaoClient } from '../../api/bao'
import * as grants from '../../api/grants' import * as grants from '../../api/grants'
import * as ids from '../../api/identities' import * as ids from '../../api/identities'
import * as mountsApi from '../../api/mounts'
import * as api from '../../api/secrets' import * as api from '../../api/secrets'
import { SessionProvider } from '../../api/session' import { SessionProvider } from '../../api/session'
import { useSession } from '../../api/useSession' import { useSession } from '../../api/useSession'
@@ -14,8 +15,9 @@ import { SecretsPage } from './SecretsPage'
vi.mock('../../api/grants') vi.mock('../../api/grants')
vi.mock('../../api/identities') 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/secrets', async (orig) => ({ ...(await orig<typeof api>()), listMounts: vi.fn(), listSecrets: vi.fn(), readPolicyHcl: vi.fn(), writeSecret: vi.fn() }))
vi.mock('../../api/tokens') vi.mock('../../api/tokens')
vi.mock('../../api/mounts', async (orig) => ({ ...(await orig<typeof mountsApi>()), createMount: vi.fn(), tuneMount: vi.fn(), readKvConfig: vi.fn(), deleteMount: vi.fn(), mountImpact: vi.fn() }))
const client = new BaoClient('http://b', 't') const client = new BaoClient('http://b', 't')
@@ -29,7 +31,7 @@ function Connected() {
} }
beforeEach(() => { beforeEach(() => {
vi.mocked(api.listKvMounts).mockResolvedValue([{ path: 'secret/' }]) vi.mocked(api.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }])
vi.mocked(api.listSecrets).mockImplementation(async (_c, _m, prefix) => vi.mocked(api.listSecrets).mockImplementation(async (_c, _m, prefix) =>
prefix === '' prefix === ''
? [{ name: 'app/', path: 'app/', isFolder: true }] ? [{ name: 'app/', path: 'app/', isFolder: true }]
@@ -127,6 +129,157 @@ test('shows why a grant failed and keeps the form open', async () => {
expect(screen.getByRole('form', { name: 'Grant access to this secret' })).toBeInTheDocument() expect(screen.getByRole('form', { name: 'Grant access to this secret' })).toBeInTheDocument()
}) })
test('groups mounts by engine and shows the engine view for a dynamic mount', async () => {
vi.mocked(api.listMounts).mockResolvedValue([
{ path: 'database/', type: 'database' },
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'cubbyhole/', type: 'cubbyhole' },
])
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
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' }))
const select = await screen.findByLabelText('Secrets engine')
expect(within(select).getByRole('group', { name: 'KV' })).toBeInTheDocument()
expect(within(select).getByRole('group', { name: 'Database' })).toBeInTheDocument()
expect(within(select).queryByText('cubbyhole/')).not.toBeInTheDocument()
await user.selectOptions(select, 'database/')
expect(await screen.findByRole('heading', { name: /Database · database\// })).toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'New role' })).toBeInTheDocument()
expect(api.listSecrets).not.toHaveBeenCalled()
})
async function openPage() {
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' }))
return user
}
test('a server with no engines can still create its first one', async () => {
vi.mocked(api.listMounts).mockResolvedValue([])
vi.mocked(mountsApi.createMount).mockResolvedValue()
const user = await openPage()
expect(await screen.findByText('No secrets engines are mounted.')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'New secrets engine' }))
await user.type(screen.getByRole('textbox', { name: 'Path' }), 'secret')
vi.mocked(api.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }])
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(mountsApi.createMount).toHaveBeenCalled()
expect(await screen.findByRole('navigation', { name: 'Path' })).toBeInTheDocument()
expect(screen.queryByRole('region', { name: 'New secrets engine' })).not.toBeInTheDocument()
})
test('creating an engine selects it', async () => {
vi.mocked(mountsApi.createMount).mockResolvedValue()
const user = await openPage()
await user.click(await screen.findByRole('button', { name: 'New secrets engine' }))
await user.selectOptions(screen.getByLabelText('Type'), 'ssh')
await user.type(screen.getByRole('textbox', { name: 'Path' }), 'hosts')
vi.mocked(api.listMounts).mockResolvedValue([
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'hosts/', type: 'ssh' },
])
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(await screen.findByRole('heading', { name: /SSH · hosts\// })).toBeInTheDocument()
expect(screen.getByLabelText('Secrets engine')).toHaveValue('hosts/')
})
test('Settings opens the selected mount\'s settings, and toggles closed', async () => {
vi.mocked(mountsApi.readKvConfig).mockResolvedValue({ max_versions: 0, cas_required: false, delete_version_after: '0s' })
const user = await openPage()
await user.click(await screen.findByRole('button', { name: 'Settings' }))
expect(await screen.findByRole('region', { name: 'Settings for secret/' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Settings' }))
expect(screen.queryByRole('region', { name: 'Settings for secret/' })).not.toBeInTheDocument()
})
test('deleting the selected engine falls back to another', async () => {
vi.mocked(api.listMounts).mockResolvedValue([
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'hosts/', type: 'ssh' },
])
vi.mocked(mountsApi.mountImpact).mockResolvedValue({ kind: 'dynamic', roles: 0, hasLeases: false, unknown: [] })
vi.mocked(mountsApi.deleteMount).mockResolvedValue()
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
const user = await openPage()
await user.selectOptions(await screen.findByLabelText('Secrets engine'), 'hosts/')
await user.click(screen.getByRole('button', { name: 'Delete' }))
expect(await screen.findByRole('alertdialog', { name: 'Delete hosts/' })).toBeInTheDocument()
vi.mocked(api.listMounts).mockResolvedValue([{ path: 'secret/', type: 'kv', version: '2' }])
await user.type(screen.getByLabelText(/Type/), 'hosts')
await user.click(screen.getByRole('button', { name: 'Delete forever' }))
expect(mountsApi.deleteMount).toHaveBeenCalledWith(client, 'hosts/')
expect(await screen.findByRole('button', { name: 'secret/' })).toBeInTheDocument()
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
test('switching mounts closes an open delete panel', async () => {
vi.mocked(api.listMounts).mockResolvedValue([
{ path: 'secret/', type: 'kv', version: '2' },
{ path: 'hosts/', type: 'ssh' },
])
vi.mocked(mountsApi.mountImpact).mockResolvedValue({ kind: 'kv', topLevelEntries: 0, unknown: [] })
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
const user = await openPage()
await user.click(await screen.findByRole('button', { name: 'Delete' }))
expect(await screen.findByRole('alertdialog', { name: 'Delete secret/' })).toBeInTheDocument()
await user.selectOptions(screen.getByLabelText('Secrets engine'), 'hosts/')
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
test('lays out New, then the labelled engine picker with Settings and Delete, then the breadcrumbs', async () => {
await openPage()
const newButton = await screen.findByRole('button', { name: 'New secrets engine' })
const select = screen.getByLabelText('Secrets engine') // a single engine still gets its picker, so the bar looks the same
const settings = screen.getByRole('button', { name: 'Settings' })
const del = screen.getByRole('button', { name: 'Delete' })
const crumbs = screen.getByRole('navigation', { name: 'Path' })
// Settings and Delete share the picker's line
const bar = select.closest('.mount-bar')!
expect(bar).toContainElement(settings)
expect(bar).toContainElement(del)
expect(bar).not.toContainElement(newButton)
expect(bar).not.toContainElement(crumbs)
// top to bottom: New, the bar, then the breadcrumbs
const before = (a: Element, b: Element) => Boolean(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING)
expect(before(newButton, select)).toBe(true)
expect(before(bar, crumbs)).toBe(true)
expect(screen.getByRole('button', { name: 'secret/' }).closest('nav')).toBe(crumbs)
})
test('a dynamic engine uses the full width, with the same header', async () => {
vi.mocked(api.listMounts).mockResolvedValue([{ path: 'hosts/', type: 'ssh' }])
vi.spyOn(BaoClient.prototype, 'list').mockResolvedValue([])
await openPage()
expect(await screen.findByLabelText('Secrets engine')).toHaveValue('hosts/')
expect(screen.getByRole('button', { name: 'Settings' })).toBeInTheDocument()
expect(screen.queryByRole('navigation', { name: 'Path' })).not.toBeInTheDocument()
expect(document.querySelector('.secrets-layout')).toBeNull()
})
test('asks to connect first', () => { test('asks to connect first', () => {
render( render(
<QueryClientProvider client={new QueryClient()}> <QueryClientProvider client={new QueryClient()}>
@@ -139,3 +292,28 @@ test('asks to connect first', () => {
) )
expect(screen.getByText(/Not connected/)).toBeInTheDocument() 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(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<SessionProvider>
<MemoryRouter>
<Connected />
<SecretsPage />
</MemoryRouter>
</SessionProvider>
</QueryClientProvider>,
)
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' })
})
+186 -56
View File
@@ -1,21 +1,31 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useState } from 'react' import { useId, useState } from 'react'
import type { BaoClient } from '../../api/bao' import type { BaoClient } from '../../api/bao'
import { listKvMounts, listSecrets } from '../../api/secrets' import { engineFor, mountKind, mountTypeFor } from '../../api/engines/registry'
import { listSecrets } from '../../api/secrets'
import { RequireConnection } from '../shared/RequireConnection' import { RequireConnection } from '../shared/RequireConnection'
import { useMounts } from '../shared/useMounts'
import { AccessPanel } from './AccessPanel' 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 }) { function Browser({ client }: { client: BaoClient }) {
const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) }) const mounts = useMounts(client)
const selectId = useId()
const [mountChoice, setMount] = useState<string | null>(null) const [mountChoice, setMount] = useState<string | null>(null)
const [prefix, setPrefix] = useState('') const [prefix, setPrefix] = useState('')
const [selected, setSelected] = useState<string | null>(null) const [selected, setSelected] = useState<string | null>(null)
const [dialog, setDialog] = useState<'create' | 'edit' | 'delete' | 'secret' | null>(null)
const mount = mountChoice ?? mounts.data?.[0]?.path ?? null const current = mounts.data?.find((m) => m.path === mountChoice) ?? mounts.data?.[0] ?? null
const mount = current?.path ?? null
const isKv = current !== null && mountKind(current) === 'kv'
const entries = useQuery({ const entries = useQuery({
queryKey: ['kv-list', mount, prefix], queryKey: ['kv-list', mount, prefix],
queryFn: () => listSecrets(client, mount!, prefix), queryFn: () => listSecrets(client, mount!, prefix),
enabled: mount !== null, enabled: isKv,
}) })
const crumbs = prefix.split('/').filter(Boolean) const crumbs = prefix.split('/').filter(Boolean)
@@ -26,64 +36,184 @@ function Browser({ client }: { client: BaoClient }) {
if (mounts.error) return <p role="alert">{mounts.error.message}</p> if (mounts.error) return <p role="alert">{mounts.error.message}</p>
if (mounts.isPending) return <p>Loading…</p> if (mounts.isPending) return <p>Loading…</p>
if (!mount) return <p>No KV v2 secrets engines are mounted.</p>
const existing = mounts.data.map((m) => m.path)
const closeDialog = () => setDialog(null)
const newButton = (
<div className="mount-new">
<button type="button" onClick={() => setDialog(dialog === 'create' ? null : 'create')} aria-expanded={dialog === 'create'}>
New secrets engine
</button>
</div>
)
const dialogs = dialog === 'delete' && current ? (
<DeleteMountDialog
key={current.path}
client={client}
mount={current}
onClose={closeDialog}
onDeleted={() => {
closeDialog()
// Fall back to the first remaining mount.
setMount(null)
go('')
}}
/>
) : dialog && dialog !== 'delete' && dialog !== 'secret' && (
<MountDialog
// Remount per mount so one mount's settings are never shown (or saved) for another.
key={dialog === 'edit' ? current?.path : 'create'}
client={client}
existing={existing}
mount={dialog === 'edit' && current ? current : undefined}
onClose={closeDialog}
onDone={(path) => {
closeDialog()
// A new mount starts at its root; saving settings keeps your place.
if (path !== mount) {
setMount(path)
go('')
}
}}
/>
)
if (!current || !mount) {
return (
<>
<p>No secrets engines are mounted.</p>
{newButton}
{dialogs}
</>
)
}
const where = prefix ? `${mount}${prefix}` : mount const where = prefix ? `${mount}${prefix}` : mount
const kv = mounts.data.filter((m) => mountKind(m) === 'kv')
const dynamic = mounts.data.filter((m) => mountKind(m) === 'dynamic')
// New engine on its own line; then the engine picker with what you can do to it; then (for KV) where you are in it.
const header = (
<>
{newButton}
<div className="mount-bar">
<div className="mount-pick">
<label htmlFor={selectId}>Secrets engine</label>
<select
id={selectId}
value={mount}
onChange={(e) => {
setMount(e.target.value)
go('')
// A settings or delete panel belongs to the mount it was opened for.
setDialog(null)
}}
>
{kv.length > 0 && (
<optgroup label="KV">
{kv.map((m) => (
<option key={m.path}>{m.path}</option>
))}
</optgroup>
)}
{[...new Set(dynamic.map((m) => m.type))].map((type) => (
<optgroup key={type} label={engineFor(type).label}>
{dynamic
.filter((m) => m.type === type)
.map((m) => (
<option key={m.path}>{m.path}</option>
))}
</optgroup>
))}
</select>
</div>
<div className="mount-actions">
{mountTypeFor(current) && (
<button type="button" onClick={() => setDialog(dialog === 'edit' ? null : 'edit')} aria-expanded={dialog === 'edit'}>
Settings
</button>
)}
{isKv && (
<button type="button" onClick={() => setDialog(dialog === 'secret' ? null : 'secret')} aria-expanded={dialog === 'secret'}>
New secret
</button>
)}
<button type="button" onClick={() => setDialog(dialog === 'delete' ? null : 'delete')} aria-expanded={dialog === 'delete'}>
Delete
</button>
</div>
</div>
{dialogs}
{dialog === 'secret' && isKv && (
<NewSecretDialog
key={`${mount}${prefix}`}
client={client}
mount={mount}
prefix={prefix}
onClose={closeDialog}
onDone={(path) => {
closeDialog()
const folder = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : ''
setPrefix(folder)
setSelected(path)
}}
/>
)}
</>
)
if (!isKv) {
return (
<>
{header}
<EngineView client={client} mount={current} />
</>
)
}
return ( return (
<div className="secrets-layout"> <>
<div className="secrets-browser"> {header}
<nav aria-label="Path" className="crumbs"> <nav aria-label="Path" className="crumbs">
{mounts.data.length > 1 && ( <button type="button" onClick={() => go('')}>
<select {mount}
aria-label="Mount" </button>
value={mount} {crumbs.map((c, i) => (
onChange={(e) => { <button key={i} type="button" onClick={() => go(crumbs.slice(0, i + 1).join('/') + '/')}>
setMount(e.target.value) {c}/
go('')
}}
>
{mounts.data.map((m) => (
<option key={m.path}>{m.path}</option>
))}
</select>
)}
<button type="button" onClick={() => go('')}>
{mount}
</button> </button>
{crumbs.map((c, i) => ( ))}
<button key={i} type="button" onClick={() => go(crumbs.slice(0, i + 1).join('/') + '/')}> </nav>
{c}/ <div className="secrets-layout">
</button> <div className="secrets-browser">
))} {entries.isPending && <p className="hint">Loading…</p>}
</nav> {entries.error && <p role="alert">{entries.error.message}</p>}
{entries.isPending && <p className="hint">Loading…</p>} {entries.data?.length === 0 && <p className="hint">No secrets in {where} yet.</p>}
{entries.error && <p role="alert">{entries.error.message}</p>} {!!entries.data?.length && (
{entries.data?.length === 0 && <p className="hint">No secrets in {where} yet.</p>} <ul className="entries" aria-label={`Contents of ${where}`}>
{!!entries.data?.length && ( {entries.data.map((e) => (
<ul className="entries" aria-label={`Contents of ${where}`}> <li key={e.path}>
{entries.data.map((e) => ( <button
<li key={e.path}> type="button"
<button className={e.isFolder ? 'entry-folder' : undefined}
type="button" aria-pressed={e.isFolder ? undefined : selected === e.path}
className={e.isFolder ? 'entry-folder' : undefined} onClick={() => (e.isFolder ? go(e.path) : setSelected(e.path))}
aria-pressed={e.isFolder ? undefined : selected === e.path} >
onClick={() => (e.isFolder ? go(e.path) : setSelected(e.path))} {e.name}
> {e.isFolder && <span aria-hidden="true">›</span>}
{e.name} </button>
{e.isFolder && <span aria-hidden="true">›</span>} </li>
</button> ))}
</li> </ul>
))} )}
</ul> </div>
{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>
)} )}
</div> </div>
{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>
)}
</div>
) )
} }
@@ -0,0 +1,23 @@
import { DYNAMIC_ACCESS, type DynamicAccess } from '../../model/managed'
/** Checkboxes for what a grant on a dynamic-engine role allows. */
export function DynamicAccessPicker({ value, onChange }: { value: DynamicAccess[]; onChange: (v: DynamicAccess[]) => void }) {
return (
<fieldset className="caps">
<legend>Access</legend>
{DYNAMIC_ACCESS.map((a) => (
<label key={a.id} className="check">
<input
type="checkbox"
checked={value.includes(a.id)}
onChange={(e) => onChange(e.target.checked ? [...value, a.id] : value.filter((x) => x !== a.id))}
/>
<span>
{a.label}
<span className="hint"> {a.help}</span>
</span>
</label>
))}
</fieldset>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { useQuery } from '@tanstack/react-query'
import type { BaoClient } from '../../api/bao'
import { mountKind } from '../../api/engines/registry'
import { listMounts } from '../../api/secrets'
/** KV v2 and dynamic-engine mounts (system, cubbyhole and identity mounts are left out). */
export function useMounts(client: BaoClient) {
return useQuery({
queryKey: ['mounts'],
queryFn: async () => (await listMounts(client)).filter((m) => mountKind(m) !== null),
})
}
+147 -14
View File
@@ -173,7 +173,6 @@ main:focus {
align-items: center; align-items: center;
margin-left: auto; margin-left: auto;
padding: 0 var(--s3); padding: 0 var(--s3);
color: var(--ink-faint);
font-family: var(--mono); font-family: var(--mono);
font-size: var(--text-sm); font-size: var(--text-sm);
} }
@@ -182,10 +181,6 @@ main:focus {
margin-left: auto; margin-left: auto;
} }
.shell > nav .whoami + .connect {
margin-left: 0;
}
.shell main { .shell main {
max-width: var(--measure); max-width: var(--measure);
margin: 0 auto; margin: 0 auto;
@@ -496,6 +491,39 @@ td:last-child button + button {
border-radius: 0; border-radius: 0;
} }
/* A lease is a row with its own actions, not a folder link: undo the full-width entry button style. */
.entries .lease-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s2);
padding: var(--s2) var(--s4);
}
.entries .lease-row > span {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
font-family: var(--mono);
}
.entries .lease-row button {
display: inline-block;
width: auto;
padding: 0.4rem var(--s3);
text-align: center;
font-family: inherit;
font-size: var(--text-sm);
background: var(--surface);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
}
.entries .lease-row > :is(p, dl) {
flex-basis: 100%;
margin: 0;
}
.entries [aria-pressed='true'] { .entries [aria-pressed='true'] {
background: var(--accent-soft); background: var(--accent-soft);
color: var(--accent); color: var(--accent);
@@ -888,6 +916,21 @@ td:last-child button + button {
box-shadow: 0 0 0 2px var(--accent); box-shadow: 0 0 0 2px var(--accent);
} }
/* With a node selected, its own links stand out and everything else steps back. */
.gnode-linked .gnode-card {
box-shadow: 0 0 0 1px var(--accent);
}
.gnode-dim,
.edge-dim {
opacity: 0.25;
}
.react-flow__edge.edge-linked .react-flow__edge-path {
stroke: var(--accent);
stroke-width: 2.5;
}
/* Handles anchor the edges but aren't interactive. */ /* Handles anchor the edges but aren't interactive. */
.gnode-card .react-flow__handle { .gnode-card .react-flow__handle {
width: 1px; width: 1px;
@@ -1085,14 +1128,6 @@ button.link:hover:not(:disabled) {
align-items: start; align-items: start;
} }
.secrets-browser .crumbs {
margin-top: 0;
}
.secrets-browser .crumbs select {
min-width: 0;
}
.secrets-browser .entries { .secrets-browser .entries {
max-height: 70vh; max-height: 70vh;
overflow-y: auto; overflow-y: auto;
@@ -1427,11 +1462,16 @@ button.danger-solid:hover:not(:disabled) {
cursor: pointer; cursor: pointer;
} }
.edge-label-selected { .edge-label-selected,
.edge-label-linked {
border-color: var(--accent); border-color: var(--accent);
color: var(--accent); color: var(--accent);
} }
.edge-label-dim {
opacity: 0.25;
}
/* Inline "Grant access" form inside the secret detail card. */ /* Inline "Grant access" form inside the secret detail card. */
.grant-here { .grant-here {
max-width: none; max-width: none;
@@ -1453,3 +1493,96 @@ button.danger-solid:hover:not(:disabled) {
border-radius: var(--radius); border-radius: var(--radius);
color: var(--accent); color: var(--accent);
} }
/* ---------- Dynamic engines ---------- */
.engine-view {
min-width: 0;
}
.creds-issued {
margin: var(--s4) 0;
padding: var(--s4);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.creds-issued dl {
margin: var(--s3) 0;
}
.creds-issued dt {
font-weight: 600;
}
.creds-issued dd {
margin: 0 0 var(--s3);
overflow-wrap: anywhere;
}
.creds-issued code {
font-family: var(--mono);
white-space: pre-wrap;
}
/* Top of the Secrets page: New, then the engine picker with its actions, then (KV) the breadcrumbs. */
.mount-new {
margin-bottom: var(--s4);
}
.mount-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--s3);
margin-bottom: var(--s2);
}
.mount-pick {
display: flex;
align-items: center;
gap: var(--s2);
min-width: 0;
}
.mount-pick label {
font-weight: 500;
white-space: nowrap;
}
.mount-pick select {
min-width: 12rem;
max-width: 100%;
}
.mount-actions {
display: flex;
gap: var(--s2);
}
.mount-bar + .crumbs,
.mount-dialog + .crumbs {
margin-top: var(--s2);
}
.mount-dialog {
margin: 0 0 var(--s4);
padding: var(--s4);
background: var(--surface-sunken);
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;
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, test } from 'vitest'
import { maskConnectionUrl } from './connectionUrl'
test('keeps templated credentials', () => {
const u = 'postgresql://{{username}}:{{password}}@db:5432/app?sslmode=disable'
expect(maskConnectionUrl(u)).toBe(u)
})
test('hides a literal password in the userinfo', () => {
expect(maskConnectionUrl('postgresql://bao:hunter2@db:5432/app')).toBe('postgresql://bao:••••@db:5432/app')
expect(maskConnectionUrl('mongodb+srv://u:p%40ss@cluster.example.test/x')).toBe('mongodb+srv://u:••••@cluster.example.test/x')
})
test('hides a literal password parameter, in either style', () => {
expect(maskConnectionUrl('postgresql://db/app?user=bao&password=hunter2&sslmode=disable')).toBe(
'postgresql://db/app?user=bao&password=••••&sslmode=disable',
)
expect(maskConnectionUrl('host=db user=bao password=hunter2 dbname=app')).toBe('host=db user=bao password=•••• dbname=app')
})
test('leaves URLs without credentials alone', () => {
expect(maskConnectionUrl('postgresql://db:5432/app')).toBe('postgresql://db:5432/app')
expect(maskConnectionUrl('')).toBe('')
})
+13
View File
@@ -0,0 +1,13 @@
const MASK = '••••'
/**
* A connection URL safe to put on screen. Templated passwords ("{{password}}", which OpenBao fills in itself) are
* kept, but a literal one typed into the URL ("user:secret@host", "?password=secret") is hidden.
*/
export function maskConnectionUrl(url: string): string {
return url
.replace(/^([a-z][a-z0-9+.-]*:\/\/[^:@/\s]*:)([^@/\s]*)(@)/i, (m, head: string, pw: string, at: string) =>
pw.includes('{{') ? m : `${head}${MASK}${at}`,
)
.replace(/([?&;\s]password=)([^&;\s]*)/gi, (m, head: string, pw: string) => (pw.includes('{{') ? m : `${head}${MASK}`))
}
+61
View File
@@ -0,0 +1,61 @@
import { expect, test } from 'vitest'
import { ENGINES } from '../api/engines/registry'
import { accessForPath } from './graph'
import { dynamicGrantRules, parseManagedPolicy, renderManagedPolicy } from './managed'
import { pathMatches } from './policy'
const dbRoles = ENGINES.database.roleKinds[0]
const dbStatic = ENGINES.database.roleKinds[1]
const aws = ENGINES.aws.roleKinds[0]
const ssh = ENGINES.ssh.roleKinds[0]
test('database: generate is read on creds, and is removed when not granted', () => {
expect(dynamicGrantRules(dbRoles, 'database/', 'ro', ['generate'])).toEqual([
{ path: 'database/creds/ro', capabilities: ['read'] },
{ path: 'database/roles/ro', capabilities: [] },
])
expect(dynamicGrantRules(dbStatic, 'database/', 'svc', ['generate'])[0]).toEqual({ path: 'database/static-creds/svc', capabilities: ['read'] })
})
test('manage grants role CRUD plus listing, and generate is revoked when unticked', () => {
expect(dynamicGrantRules(dbRoles, 'database', 'ro', ['manage'])).toEqual([
{ path: 'database/creds/ro', capabilities: [] },
{ path: 'database/roles/ro', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('aws and ssh use the capabilities their requests need', () => {
expect(dynamicGrantRules(aws, 'aws/', 'ci', ['generate'])[0]).toEqual({ path: 'aws/creds/ci', capabilities: ['read', 'update'] })
const s = dynamicGrantRules(ssh, 'ssh/', 'ops', ['generate'])
expect(s.slice(0, 2)).toEqual([
{ path: 'ssh/sign/ops', capabilities: ['update'] },
{ path: 'ssh/creds/ops', capabilities: ['update'] },
])
})
test('"*" grants every role of the kind', () => {
expect(dynamicGrantRules(dbRoles, 'database/', '*', ['generate', 'manage'])).toEqual([
{ path: 'database/creds/*', capabilities: ['read'] },
{ path: 'database/roles/*', capabilities: ['create', 'read', 'update', 'delete'] },
{ path: 'database/roles', capabilities: ['list'] },
])
})
test('rules survive a managed-policy round trip and resolve in the access model', () => {
const grants = dynamicGrantRules(dbRoles, 'database/', 'ro', ['generate']).filter((g) => g.capabilities.length)
const hcl = renderManagedPolicy('user', 'alice', grants)
const parsed = parseManagedPolicy(hcl)
expect(parsed.editable).toBe(true)
expect(parsed.grants).toEqual(grants)
const entries = accessForPath(
[{ kind: 'user', name: 'alice', policies: ['envbao-user-alice'] }],
[{ name: 'envbao-user-alice', hcl }],
'database/creds/ro',
pathMatches,
)
expect(entries).toHaveLength(1)
expect(entries[0].capabilities).toEqual(['read'])
expect(accessForPath([{ kind: 'user', name: 'alice', policies: ['envbao-user-alice'] }], [{ name: 'envbao-user-alice', hcl }], 'database/creds/other', pathMatches)).toEqual([])
})
+26
View File
@@ -1,3 +1,4 @@
import type { RoleKind } from '../api/engines/registry'
import { MANAGED_PREFIX } from './graph' import { MANAGED_PREFIX } from './graph'
import { CAPABILITIES, parsePolicy, type Capability } from './policy' import { CAPABILITIES, parsePolicy, type Capability } from './policy'
@@ -94,3 +95,28 @@ export function kvGrantRules(mount: string, secretPath: string, caps: KvCapabili
{ path: `${m}metadata/${secretPath}`, capabilities: caps.includes('list') ? ['list'] : [] }, { path: `${m}metadata/${secretPath}`, capabilities: caps.includes('list') ? ['list'] : [] },
] ]
} }
/** What a grant on a dynamic-engine role can allow. */
export type DynamicAccess = 'generate' | 'manage'
export const DYNAMIC_ACCESS: { id: DynamicAccess; label: string; help: string }[] = [
{ id: 'generate', label: 'Generate credentials', help: 'Issue database logins, AWS keys, SSH certificates or OTPs from the role.' },
{ id: 'manage', label: 'Manage role', help: 'View, change and delete the role, and list the roles of this kind.' },
]
/**
* Expand a grant on a dynamic-engine role (`role` may be "*" for every role of that kind) into API-path rules.
* Like kvGrantRules, a path that is not granted comes back with no capabilities so that writing the rules removes it;
* the shared "list roles" path is only emitted when managing, so revoking one role never hides the others.
*/
export function dynamicGrantRules(roleKind: RoleKind, mount: string, role: string, access: DynamicAccess[]): Grant[] {
const m = mount.endsWith('/') ? mount : `${mount}/`
const rules: Grant[] = roleKind.creds.map((c) => ({
path: m + c.path(role),
capabilities: access.includes('generate') ? c.capabilities : [],
}))
const manage = access.includes('manage')
rules.push({ path: `${m}${roleKind.path}/${role}`, capabilities: manage ? ['create', 'read', 'update', 'delete'] : [] })
if (manage) rules.push({ path: `${m}${roleKind.path}`, capabilities: ['list'] })
return rules
}
+45
View File
@@ -0,0 +1,45 @@
import { expect, test } from 'vitest'
import { policiesReferencing, validateMountPath, validateSecretPath } from './mounts'
const existing = ['secret/', 'database/', 'team/kv/']
test('accepts ordinary and nested paths, with or without slashes', () => {
for (const p of ['scratch', 'my-store_2', 'scratch/', 'apps/payments', '9lives']) expect(validateMountPath(p, existing), p).toBeNull()
})
test('rejects empty, oddly-formed and uppercase paths', () => {
expect(validateMountPath('', existing)).toBe('Path is required.')
expect(validateMountPath('/', existing)).toBe('Path is required.')
expect(validateMountPath(' x', existing)).toMatch(/spaces/)
for (const p of ['My Store', 'Upper', 'a//b', '-lead', 'dot.ted', 'a/_b', 'ünï']) expect(validateMountPath(p, existing), p).toMatch(/lowercase/)
})
test('rejects the names OpenBao reserves, also as a prefix', () => {
for (const p of ['sys', 'auth', 'identity', 'cubbyhole', 'sys/x', 'auth/kv']) expect(validateMountPath(p, existing), p).toMatch(/reserved/)
})
test('rejects a path equal to, inside or containing an existing mount', () => {
expect(validateMountPath('secret', existing)).toMatch(/already a secrets engine/)
expect(validateMountPath('secret/', existing)).toMatch(/already/)
expect(validateMountPath('secret/inner', existing)).toMatch(/inside the existing mount "secret\/"/)
expect(validateMountPath('team', existing)).toMatch(/contain the existing mount "team\/kv\/"/)
expect(validateMountPath('secrets', existing)).toBeNull() // shares a prefix, not a path segment
})
test('finds policies with rules under a mount, however the mount is written', () => {
const policies = [
{ name: 'b-uses', hcl: 'path "secret/data/app/*" { capabilities = ["read"] }' },
{ name: 'a-uses', hcl: 'path "secret/metadata/*" { capabilities = ["list"] }\npath "x/y" { capabilities = ["read"] }' },
{ name: 'other', hcl: 'path "secrets/data/x" { capabilities = ["read"] }' },
{ name: 'unreadable', hcl: null },
{ name: 'broken', hcl: 'path "secret/x" {' },
]
expect(policiesReferencing(policies, 'secret/')).toEqual(['a-uses', 'b-uses'])
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()
})
+55
View File
@@ -0,0 +1,55 @@
import { parsePolicy } from './policy'
/** Prefixes OpenBao reserves for itself; a secrets engine cannot be mounted at or under them. */
const RESERVED = ['sys', 'auth', 'identity', 'cubbyhole']
const SEGMENT = /^[a-z0-9][a-z0-9_-]*$/
const norm = (p: string) => p.replace(/^\/+|\/+$/g, '')
/**
* Error message for a mount path that can't be used, or null. `existing` are the current mounts (with or without
* trailing slashes). Nested paths such as "team/kv" are fine, but a mount can't sit inside another or contain one.
*/
export function validateMountPath(path: string, existing: string[]): string | null {
const p = norm(path)
if (!p) return 'Path is required.'
if (path !== path.trim()) return 'Path must not start or end with spaces.'
if (!p.split('/').every((s) => SEGMENT.test(s))) {
return 'Use lowercase letters, digits, "-" and "_", starting each part with a letter or digit. Parts are separated by "/".'
}
const first = p.split('/')[0]
if (RESERVED.includes(first)) return `"${first}" is reserved by OpenBao.`
for (const e of existing.map(norm)) {
if (e === p) return `"${p}/" is already a secrets engine.`
if (p.startsWith(`${e}/`)) return `"${p}/" would sit inside the existing mount "${e}/".`
if (e.startsWith(`${p}/`)) return `"${p}/" would contain the existing mount "${e}/".`
}
return null
}
export interface PolicyText {
name: string
/** Null when the policy could not be read. */
hcl: string | null
}
/** Policies with a rule on a path under `mount`, which would be left pointing at nothing if it were deleted. */
export function policiesReferencing(policies: PolicyText[], mount: string): string[] {
const m = mount.endsWith('/') ? mount : `${mount}/`
return policies
.filter((p) => p.hcl !== null && parsePolicy(p.hcl).rules.some((r) => r.path.startsWith(m)))
.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
}
+3 -2
View File
@@ -22,7 +22,7 @@ test.each([
expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument() expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument()
}) })
test('redirects / to identities', () => { test('redirects / to the connect page while signed out', () => {
const router = createMemoryRouter(routes, { initialEntries: ['/'] }) const router = createMemoryRouter(routes, { initialEntries: ['/'] })
render( render(
<Providers> <Providers>
@@ -31,5 +31,6 @@ test('redirects / to identities', () => {
</SessionProvider> </SessionProvider>
</Providers>, </Providers>,
) )
expect(screen.getByRole('heading', { name: 'Identities' })).toBeInTheDocument() expect(screen.getByRole('heading', { name: 'Connect' })).toBeInTheDocument()
expect(router.state.location.pathname).toBe('/connect')
}) })
+3 -2
View File
@@ -1,15 +1,16 @@
import { Navigate, type RouteObject } from 'react-router' import type { RouteObject } from 'react-router'
import { ConnectPage } from './features/connect/ConnectPage' import { ConnectPage } from './features/connect/ConnectPage'
import { GraphPage } from './features/graph/GraphPage' import { GraphPage } from './features/graph/GraphPage'
import { IdentitiesPage } from './features/identities/IdentitiesPage' import { IdentitiesPage } from './features/identities/IdentitiesPage'
import { SecretsPage } from './features/secrets/SecretsPage' import { SecretsPage } from './features/secrets/SecretsPage'
import { Home } from './Home'
import { Layout } from './Layout' import { Layout } from './Layout'
export const routes: RouteObject[] = [ export const routes: RouteObject[] = [
{ {
element: <Layout />, element: <Layout />,
children: [ children: [
{ index: true, element: <Navigate to="/identities" replace /> }, { index: true, element: <Home /> },
{ path: 'connect', element: <ConnectPage /> }, { path: 'connect', element: <ConnectPage /> },
{ path: 'identities', element: <IdentitiesPage /> }, { path: 'identities', element: <IdentitiesPage /> },
{ path: 'secrets', element: <SecretsPage /> }, { path: 'secrets', element: <SecretsPage /> },
+29
View File
@@ -0,0 +1,29 @@
import type { DraftValue } from '../api/engines/roles'
/**
* A Postgres for the database-engine integration tests, from BAO_PG_URL, e.g.
* postgresql://postgres:secret@postgres:5432/app?sslmode=disable. The host must be reachable from OpenBao (not
* necessarily from the test process). The user needs CREATEROLE. Returns null when unset, so tests can skip.
*/
export function pgTarget(): { values: Record<string, DraftValue>; creationStatements: string } | null {
const raw = process.env.BAO_PG_URL
if (!raw) return null
const u = new URL(raw)
const db = u.pathname.slice(1)
return {
values: {
plugin_name: 'postgresql-database-plugin',
// OpenBao substitutes the admin login into the template, so the password never sits in the URL it stores.
connection_url: `${u.protocol}//{{username}}:{{password}}@${u.host}${u.pathname}${u.search}`,
allowed_roles: '*',
username: decodeURIComponent(u.username),
password: decodeURIComponent(u.password),
verify_connection: true,
},
// Two statements separated by a blank line, which is how the form takes them.
creationStatements: [
`CREATE ROLE "{{name}}" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';`,
`GRANT CONNECT ON DATABASE "${db}" TO "{{name}}";`,
].join('\n\n'),
}
}
+5 -1
View File
@@ -4,6 +4,10 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({ export default defineConfig({
test: { test: {
include: ['src/**/*.integration.test.ts'], include: ['src/**/*.integration.test.ts'],
testTimeout: 15000, testTimeout: 30000,
// Generating an SSH CA key in a beforeAll took over 10s on the CI runner.
hookTimeout: 60000,
// The files share one OpenBao and one Postgres: concurrent role creation fails with "tuple concurrently updated".
fileParallelism: false,
}, },
}) })