Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(console): give the managed stack the two database roles it now needs (CHOO-2623)

Wojciech Wojtyniak3473efe145fb
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
index 594273279..c0d3bdc82 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts
@@ -7,6 +7,7 @@ import type { LocalServerSecrets } from './secret-values';
const secrets: LocalServerSecrets = {
dbPassword: 'db-pw',
+ dbRuntimePassword: 'db-runtime-pw',
agentRegistrationToken: 'agent-token',
jwtSecretKey: 'jwt-key',
gatewayAdminPassword: 'gw-admin',
@@ -57,7 +58,8 @@ describe('buildEnvFile', () => {
});
it('injects every secret into its env var', () => {
- expect(vars.DB_PASSWORD).toBe('db-pw');
+ expect(vars.DB_PASSWORD).toBe('db-runtime-pw');
+ expect(vars.DB_OWNER_PASSWORD).toBe('db-pw');
expect(vars.AGENT_REGISTRATION_TOKEN).toBe('agent-token');
expect(vars.JWT_SECRET_KEY).toBe('jwt-key');
expect(vars.GATEWAY_ADMIN_PASSWORD).toBe('gw-admin');
@@ -65,6 +67,14 @@ describe('buildEnvFile', () => {
expect(vars.MATTERMOST_USER_PASSWORD).toBe('mm-user');
});
+ it('runs switch-core as the restricted runtime role, not the schema owner', () => {
+ // The runtime role name is fixed (switch_app), not derived from the
+ // secrets bundle: init-db creates exactly this role, so drifting the name
+ // here would create a role nothing grants access to.
+ expect(vars.DB_USER).toBe('switch_app');
+ expect(vars.DB_OWNER_USER).toBe('postgres');
+ });
+
it('defines every var the bundled compose file interpolates', () => {
// Derived from the compose file rather than a hand-kept list. The previous
// list had drifted both ways — it omitted GATEWAY_PUBLIC_URL (so the
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts
index 260b509bc..75a2781bd 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts
@@ -41,8 +41,16 @@ export function buildEnvFile(params: LocalServerEnvParams): string {
'',
'DB_HOST=postgres',
'DB_PORT=5432',
- 'DB_USER=postgres',
- `DB_PASSWORD=${secrets.dbPassword}`,
+ // The runtime role switch-core actually serves requests as. It owns
+ // nothing and is NOBYPASSRLS, so row-level security applies to it — see
+ // the `postgres`/`init-db` services in the bundled compose. `postgres`
+ // stays the schema owner, bootstrapped as POSTGRES_USER/POSTGRES_PASSWORD
+ // below; switch-core migrates and grants as the owner, then serves
+ // requests as this role.
+ 'DB_USER=switch_app',
+ `DB_PASSWORD=${secrets.dbRuntimePassword}`,
+ 'DB_OWNER_USER=postgres',
+ `DB_OWNER_PASSWORD=${secrets.dbPassword}`,
'DB_NAME=switch',
'',
'MATRIX_SERVER_NAME=localhost',
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
index 79d2acd00..f1d5b1bc7 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -58,8 +58,13 @@ services:
ports:
- "${SWITCH_BIND_ADDR:-127.0.0.1}:${POSTGRES_HOST_PORT:-5432}:5432"
environment:
- POSTGRES_USER: ${DB_USER}
- POSTGRES_PASSWORD: ${DB_PASSWORD}
+ # The container's bootstrapped superuser is the SCHEMA OWNER
+ # (DB_OWNER_USER), not the runtime role Switch serves requests as
+ # (DB_USER). Row-level security is inert against a table's owner, so
+ # the role every request authenticates as must be a separate, deliberately
+ # unprivileged login — created below by init-db, once the owner is up.
+ POSTGRES_USER: ${DB_OWNER_USER}
+ POSTGRES_PASSWORD: ${DB_OWNER_PASSWORD}
POSTGRES_DB: ${DB_NAME}
volumes:
# Kept deliberately after Tuwunel was removed. It still holds every media
@@ -68,7 +73,7 @@ services:
# release than the one that stops reading it.
- pgdata:/var/lib/postgresql/data
healthcheck:
- test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
+ test: ["CMD-SHELL", "pg_isready -U ${DB_OWNER_USER}"]
interval: 2s
timeout: 3s
retries: 10
@@ -77,24 +82,50 @@ services:
image: postgres:16-alpine
profiles: ["collab"]
environment:
- PGPASSWORD: ${DB_PASSWORD}
+ PGPASSWORD: ${DB_OWNER_PASSWORD}
+ # Runs as the owner: creating a database and a role both need privileges
+ # the runtime role is deliberately never given. Note the mixed quoting in
+ # the CREATE ROLE / ALTER ROLE statements is not optional — DB_USER is an
+ # identifier (double-quoted, and safe only because .env.example pins it to
+ # a fixed, non-attacker-controlled name) and the password is a string
+ # literal (single-quoted); swapping them would either fail to parse or
+ # quietly create a role named after the password.
+ #
+ # No GRANT here on purpose: on a fresh volume there is nothing yet to
+ # grant. The `switch` database has no tables until switch-core runs
+ # Alembic against the owner connection, so the runtime role's CRUD grants
+ # are issued by switch-core itself at boot, immediately after migrating.
+ # This step only has to make the role exist.
+ #
+ # The trailing ALTER ROLE is what keeps a regenerated .env working on a
+ # reused pgdata volume: the CREATE ROLE guard above skips a role that
+ # already exists, so without it a new DB_PASSWORD would never reach
+ # Postgres. DB_OWNER_PASSWORD gets no such reapplication — it is set once,
+ # as POSTGRES_PASSWORD, by the container's initial bootstrap of its own
+ # superuser, and nothing here ever reissues it. So a regenerated
+ # DB_PASSWORD takes effect on the next `up` with no rebuild, while a
+ # regenerated DB_OWNER_PASSWORD needs the stack (and its volume)
+ # recreated to match.
entrypoint: >
sh -c "
i=0
- until psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >/dev/null 2>&1; do
+ until psql -h postgres -U ${DB_OWNER_USER} -d postgres -c 'SELECT 1' >/dev/null 2>&1; do
i=$$((i+1))
if [ $$i -ge 30 ]; then
- echo 'init-db: could not connect to postgres as ${DB_USER} after 30 tries.' >&2
+ echo 'init-db: could not connect to postgres as ${DB_OWNER_USER} after 30 tries.' >&2
echo 'Last attempt:' >&2
- psql -h postgres -U ${DB_USER} -d postgres -c 'SELECT 1' >&2
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -c 'SELECT 1' >&2
echo 'A stale pgdata volume keeps the password it was first created with,' >&2
- echo 'so a regenerated DB_PASSWORD will fail here. Recreate the stack to reset it.' >&2
+ echo 'so a regenerated DB_OWNER_PASSWORD will fail here. Recreate the stack to reset it.' >&2
exit 1
fi
sleep 1
done
- psql -h postgres -U ${DB_USER} -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||
- psql -h postgres -U ${DB_USER} -d postgres -c 'CREATE DATABASE mattermost;'
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -c 'CREATE DATABASE mattermost;'
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -tc \"SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}'\" | grep -q 1 ||
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -c 'CREATE ROLE \"${DB_USER}\" LOGIN PASSWORD '\\''${DB_PASSWORD}'\\'' NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS;'
+ psql -h postgres -U ${DB_OWNER_USER} -d postgres -c 'ALTER ROLE \"${DB_USER}\" PASSWORD '\\''${DB_PASSWORD}'\\'';'
"
depends_on:
postgres:
@@ -119,7 +150,13 @@ services:
- mmdata:/mattermost/data
environment:
MM_SQLSETTINGS_DRIVERNAME: postgres
- MM_SQLSETTINGS_DATASOURCE: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/mattermost?sslmode=disable
+ # The owner's credentials, not the runtime role's: init-db creates the
+ # `mattermost` database as the owner, and the runtime role (DB_USER)
+ # neither owns it nor was granted anything on it — only `switch`'s
+ # tables get the runtime role's grants, issued by switch-core itself at
+ # boot. Mattermost's own schema has no row-level security in it, so
+ # there is no isolation reason to run it as the restricted role too.
+ MM_SQLSETTINGS_DATASOURCE: postgres://${DB_OWNER_USER}:${DB_OWNER_PASSWORD}@postgres:5432/mattermost?sslmode=disable
MM_SERVICESETTINGS_SITEURL: http://localhost:${MATTERMOST_HOST_PORT:-8065}
MM_SERVICESETTINGS_ENABLELOCALMODE: "true"
# The first-run onboarding checklist opens a modal over a dimmed page,
@@ -152,6 +189,8 @@ services:
DB_PORT: "5432"
DB_USER: ${DB_USER}
DB_PASSWORD: ${DB_PASSWORD}
+ DB_OWNER_USER: ${DB_OWNER_USER}
+ DB_OWNER_PASSWORD: ${DB_OWNER_PASSWORD}
DB_NAME: ${DB_NAME}
MATRIX_SERVER_NAME: localhost
AGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts
index 1e6d12877..f5a924ce5 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secret-values.ts
@@ -2,9 +2,18 @@ import { randomBytes } from 'node:crypto';
/** The randomly-generated secrets the local stack needs. These are the source of
* truth (kept in the OS-encrypted app-secrets store); the on-disk `.env` docker
- * reads is derived from them at each start. */
+ * reads is derived from them at each start.
+ *
+ * `dbPassword` is the schema owner's password (`DB_OWNER_PASSWORD` in the
+ * `.env`, `POSTGRES_PASSWORD` for the container) — kept under its original
+ * field name because the Postgres volume on every existing install was
+ * bootstrapped with it, and renaming the field here does not rename what is
+ * already on disk. `dbRuntimePassword` is the separate, unprivileged runtime
+ * role (`DB_PASSWORD`/`DB_USER=switch_app`) that switch-core actually serves
+ * requests as; see `init-db` in `deploy/local/standalone-docker-compose.yml`. */
export type LocalServerSecrets = {
dbPassword: string;
+ dbRuntimePassword: string;
agentRegistrationToken: string;
jwtSecretKey: string;
gatewayAdminPassword: string;
@@ -21,6 +30,7 @@ function token(bytes = 24): string {
export function generateSecrets(): LocalServerSecrets {
return {
dbPassword: token(),
+ dbRuntimePassword: token(),
agentRegistrationToken: token(),
jwtSecretKey: token(32),
gatewayAdminPassword: token(),
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts
index e7658f0ed..6d4c38a77 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.test.ts
@@ -61,6 +61,21 @@ describe('loadOrCreateSecrets', () => {
expect(setSecret).not.toHaveBeenCalled();
});
+ it('backfills a missing runtime password on an install predating the runtime role', async () => {
+ const legacy = generateSecrets() as Partial<ReturnType<typeof generateSecrets>>;
+ delete legacy.dbRuntimePassword;
+ getSecret.mockResolvedValue(JSON.stringify(legacy));
+
+ const secrets = await loadOrCreateSecrets({ secretsKey: 'host-a' });
+
+ // Every field the install already had survives untouched — in particular
+ // dbPassword, the owner password the Postgres volume was bootstrapped
+ // with, which regenerating would lock the stack out of.
+ expect(secrets).toMatchObject(legacy);
+ expect(secrets.dbRuntimePassword).toBeTruthy();
+ expect(setSecret).toHaveBeenCalledWith('host-a', JSON.stringify(secrets));
+ });
+
it('fails loud on an unreadable bundle instead of regenerating over a live volume', async () => {
getSecret.mockResolvedValue('not json');
@@ -101,4 +116,16 @@ describe('readSecrets', () => {
await expect(readSecrets({ secretsKey: 'host-a' })).resolves.toBeNull();
expect(setSecret).not.toHaveBeenCalled();
});
+
+ it('backfills a missing runtime password for display without persisting it', async () => {
+ const legacy = generateSecrets() as Partial<ReturnType<typeof generateSecrets>>;
+ delete legacy.dbRuntimePassword;
+ getSecret.mockResolvedValue(JSON.stringify(legacy));
+
+ const secrets = await readSecrets({ secretsKey: 'host-a' });
+
+ expect(secrets).toMatchObject(legacy);
+ expect(secrets?.dbRuntimePassword).toBeTruthy();
+ expect(setSecret).not.toHaveBeenCalled();
+ });
});
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts
index b56619f0b..df47f8d74 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/secrets.ts
@@ -31,6 +31,29 @@ async function readStoredSecrets(host: Pick<ServerHost, 'secretsKey'>): Promise<
}
}
+/**
+ * `dbRuntimePassword` did not exist before switch-core split its database
+ * connection into an owner role and a restricted runtime role, so a bundle
+ * stored before that split parses as `LocalServerSecrets` with that one field
+ * missing. Filling it in is safe in a way regenerating the bundle is not:
+ * nothing on the existing Postgres volume was ever created with it, since the
+ * runtime role did not exist yet either. `init-db` creates that role and
+ * `ALTER ROLE`s its password idempotently on every start (see
+ * `deploy/local/standalone-docker-compose.yml`), so whatever value lands here
+ * simply becomes the role's password on the next start, the same way a
+ * freshly generated bundle's would.
+ */
+function withRuntimePassword(secrets: LocalServerSecrets): {
+ secrets: LocalServerSecrets;
+ migrated: boolean;
+} {
+ if (secrets.dbRuntimePassword) return { secrets, migrated: false };
+ return {
+ secrets: { ...secrets, dbRuntimePassword: generateSecrets().dbRuntimePassword },
+ migrated: true,
+ };
+}
+
/**
* Return the host's stored secret bundle, generating and persisting one on first
* use. Reusing the same secrets across restarts is required — the Postgres
@@ -42,7 +65,12 @@ export async function loadOrCreateSecrets(
host: Pick<ServerHost, 'secretsKey'>
): Promise<LocalServerSecrets> {
const stored = await readStoredSecrets(host);
- if (stored.kind === 'present') return stored.secrets;
+ if (stored.kind === 'present') {
+ const { secrets, migrated } = withRuntimePassword(stored.secrets);
+ if (migrated)
+ await encryptedAppSecretsStore.setSecret(host.secretsKey, JSON.stringify(secrets));
+ return secrets;
+ }
if (stored.kind === 'unreadable') {
throw new Error(
`The stored credentials for this managed server are unreadable. Generating replacements ` +
@@ -65,12 +93,16 @@ export async function loadOrCreateSecrets(
* *display* or inspect the credentials rather than run the stack. Generating a
* bundle as a side effect of reading would mint credentials that match no
* running deployment, which is exactly the fiction a reader must not be shown.
+ * A missing `dbRuntimePassword` is backfilled in memory for callers that expect
+ * the full shape, but — unlike {@link loadOrCreateSecrets} — not persisted: a
+ * reader must not mutate stored state, so the value shown here can differ from
+ * the one the next real start assigns and persists.
*/
export async function readSecrets(
host: Pick<ServerHost, 'secretsKey'>
): Promise<LocalServerSecrets | null> {
const stored = await readStoredSecrets(host);
- return stored.kind === 'present' ? stored.secrets : null;
+ return stored.kind === 'present' ? withRuntimePassword(stored.secrets).secrets : null;
}
/** Drop the host's secret bundle so the next start generates fresh credentials.