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>
This commit is contained in:
1 parent
0eff098140
commit
11c9483a88
15 files changed
+399
-5
No files matched your search
@@ -33,9 +33,20 @@ jobs:
|
||||
BAO_DEV_ROOT_TOKEN_ID: root
|
||||
BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200
|
||||
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:
|
||||
BAO_ADDR: http://openbao:8200
|
||||
BAO_TOKEN: root
|
||||
BAO_PG_URL: postgresql://postgres:postgres@postgres:5432/app?sslmode=disable
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
|
||||
@@ -33,9 +33,20 @@ jobs:
|
||||
BAO_DEV_ROOT_TOKEN_ID: root
|
||||
BAO_DEV_LISTEN_ADDRESS: 0.0.0.0:8200
|
||||
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:
|
||||
BAO_ADDR: http://openbao:8200
|
||||
BAO_TOKEN: root
|
||||
BAO_PG_URL: postgresql://postgres:postgres@postgres:5432/app?sslmode=disable
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
|
||||
@@ -34,6 +34,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.
|
||||
|
||||
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`.
|
||||
|
||||
## OpenBao setup
|
||||
@@ -97,7 +104,7 @@ The AWS engine is not built into every OpenBao release (some ship it as an exter
|
||||
|
||||
### 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
|
||||
# Least-privilege policy for the account that uses EnvBao Admin.
|
||||
@@ -245,6 +252,10 @@ 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 dynamic-engine tests mount their own `ssh` engine (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.
|
||||
|
||||
## Limitations
|
||||
|
||||
+33
-2
@@ -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
|
||||
# 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:
|
||||
openbao:
|
||||
image: openbao/openbao:latest
|
||||
@@ -15,13 +17,30 @@ services:
|
||||
interval: 2s
|
||||
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
|
||||
# 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:
|
||||
image: openbao/openbao:latest
|
||||
depends_on:
|
||||
openbao:
|
||||
condition: service_healthy
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
BAO_ADDR: http://openbao:8200
|
||||
BAO_TOKEN: root
|
||||
@@ -30,6 +49,18 @@ services:
|
||||
entrypoint: ["sh", "/seed.sh"]
|
||||
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:
|
||||
build: .
|
||||
depends_on:
|
||||
|
||||
@@ -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;
|
||||
@@ -37,6 +37,12 @@ path "secret/data/team-a/*" {
|
||||
path "secret/metadata/team-a/*" {
|
||||
capabilities = ["list"]
|
||||
}
|
||||
path "database/creds/readonly" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "ssh/sign/demo" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
POLICY
|
||||
|
||||
bao policy write envbao-user-bob - >/dev/null <<'POLICY'
|
||||
@@ -58,6 +64,9 @@ path "secret/data/app/*" {
|
||||
path "secret/metadata/app/*" {
|
||||
capabilities = ["list"]
|
||||
}
|
||||
path "database/creds/*" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
POLICY
|
||||
|
||||
# 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 ---
|
||||
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 "Dynamic engines: database/ (Postgres) and ssh/ (certificates for the sshd service, port 2222)."
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -6,11 +6,12 @@ import * as ids from './identities'
|
||||
import * as secrets from './secrets'
|
||||
import * as tokens from './tokens'
|
||||
import { kvGrantRules } from '../model/managed'
|
||||
import { deleteConfig, readConfig, runAction } from './engines/config'
|
||||
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 { deleteRole, listRoles, readRole, writeRole } from './engines/roles'
|
||||
import { pgTarget } from '../test/postgres'
|
||||
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
|
||||
// documented least-privilege policy can't silently drift from what the app needs.
|
||||
@@ -155,3 +156,50 @@ describe('the admin policy covers dynamic engines (ssh at the default mount)', (
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
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}}')
|
||||
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([])
|
||||
})
|
||||
})
|
||||
@@ -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'),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user