OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ops: put bull-board behind reusable admin credentials
Carl-Gerhard Lindesvärdfb0b56977c82
diff --git a/apps/api/src/config/env.test.ts b/apps/api/src/config/env.test.tsindex 8492175a6..7cce932a6 100644--- a/apps/api/src/config/env.test.ts+++ b/apps/api/src/config/env.test.ts@@ -202,6 +202,20 @@ describe('derived values, computed once in the transform', () => {).toBe('https://own');});+ it('adminAuth needs both halves or neither', () => {+ expect(loadConfig(base).core.adminAuth).toBeUndefined();+ expect(+ loadConfig({ ...base, ADMIN_USERNAME: 'ops', ADMIN_PASSWORD: 'pw' }).core+ .adminAuth+ ).toEqual({ username: 'ops', password: 'pw' });+ expect(() => loadConfig({ ...base, ADMIN_USERNAME: 'ops' })).toThrow(+ 'ADMIN_PASSWORD'+ );+ expect(() => loadConfig({ ...base, ADMIN_PASSWORD: 'pw' })).toThrow(+ 'ADMIN_USERNAME'+ );+ });+it('clickhouseClustered is CLICKHOUSE_CLUSTER alone, the rule the migrations use', () => {expect(loadConfig(base).core.clickhouseClustered).toBe(false);expect(diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.tsindex 4a52f0ed8..c04771201 100644--- a/apps/api/src/config/env.ts+++ b/apps/api/src/config/env.ts@@ -405,6 +405,9 @@ const rawSchema = z.object({ENABLED_QUEUES: enabledQueuesSchema,DISABLE_WORKERS: definedIsTrueSchema,DISABLE_BULLBOARD: trueOrOneSchema,+ /** HTTP Basic credentials for operator-only surfaces; bull-board today. */+ ADMIN_USERNAME: optionalString,+ ADMIN_PASSWORD: optionalString,// --- HTTP surface ---/**@@ -653,6 +656,20 @@ function kafkaSslEnabled(raw: RawEnv): boolean {return raw.KAFKA_SSL ?? saslEnabled;}+/** Half an operator credential pair protects nothing; say so at boot. */+function checkAdminAuthIsComplete(raw: RawEnv, ctx: z.RefinementCtx): void {+ const hasUsername = raw.ADMIN_USERNAME !== undefined;+ const hasPassword = raw.ADMIN_PASSWORD !== undefined;+ if (hasUsername === hasPassword) {+ return;+ }+ const missing = hasUsername ? 'ADMIN_PASSWORD' : 'ADMIN_USERNAME';+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Admin auth is partially configured: ${missing} is missing (both ADMIN_USERNAME and ADMIN_PASSWORD are required)`,+ });+}+/** Half a credential pair, or a mechanism with none, is a misconfiguration. */function checkKafkaSaslIsComplete(raw: RawEnv, ctx: z.RefinementCtx): void {const hasUsername = raw.KAFKA_SASL_USERNAME !== undefined;@@ -818,6 +835,10 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {// without that flag (dev, a cloud box that never set it) mutate tables the// migrations never created, so cohorts never computed and deletions failed.clickhouseClustered: raw.CLICKHOUSE_CLUSTER,+ adminAuth:+ raw.ADMIN_USERNAME && raw.ADMIN_PASSWORD+ ? { username: raw.ADMIN_USERNAME, password: raw.ADMIN_PASSWORD }+ : undefined,encryptionKey: raw.ENCRYPTION_KEY,pingDisabled: raw.DISABLE_PING,logging: {@@ -997,6 +1018,7 @@ const envSchema = rawSchemacheckOtlpHasKey(raw, ctx);checkKafkaHeartbeatFitsSession(raw, ctx);checkKafkaSaslIsComplete(raw, ctx);+ checkAdminAuthIsComplete(raw, ctx);checkKafkaTlsOptionsHaveTls(raw, ctx);checkReaperDeadmanOutlivesSession(raw, ctx);checkVacuumOutlivesReaper(raw, ctx);diff --git a/apps/public/content/docs/self-hosting/environment-variables.mdx b/apps/public/content/docs/self-hosting/environment-variables.mdxindex 27f8eb5f9..edd321667 100644--- a/apps/public/content/docs/self-hosting/environment-variables.mdx+++ b/apps/public/content/docs/self-hosting/environment-variables.mdx@@ -731,6 +731,20 @@ Disable BullMQ board UI. Set to `true` or `1` to disable the queue monitoring daDISABLE_BULLBOARD=true```+### ADMIN_USERNAME / ADMIN_PASSWORD++**Type**: `string`+**Required**: No+**Default**: None++HTTP Basic credentials for operator-only surfaces. Today that is the queue dashboard at `/bullboard`, which can add, retry and clean jobs; it already requires a dashboard session, and these credentials narrow it from "any signed-up user" to "an operator". Set both or neither — half a pair is a startup error. The browser prompts for them.++**Example**:+```bash+ADMIN_USERNAME=ops+ADMIN_PASSWORD=$(openssl rand -hex 16)+```+### DISABLE_WORKERS**Type**: `boolean`diff --git a/packages/core/src/config.ts b/packages/core/src/config.tsindex a4a92e028..d43aff3d8 100644--- a/packages/core/src/config.ts+++ b/packages/core/src/config.ts@@ -226,6 +226,12 @@ export interface CoreConfig {demoUserId: string | undefined;/** CLICKHOUSE_CLUSTER. Must agree with what `migrate:deploy` created. */clickhouseClustered: boolean;+ /**+ * ADMIN_USERNAME / ADMIN_PASSWORD: HTTP Basic credentials for operator-only+ * surfaces (bull-board today). Undefined leaves those surfaces on their own+ * guard alone.+ */+ adminAuth: { username: string; password: string } | undefined;/** The single symmetric key for at-rest encryption; 32 bytes as 64 hex. */encryptionKey: string | undefined;/** DISABLE_PING: a self-hosted instance opts out of the usage ping. */diff --git a/packages/core/src/http/bull-board.ts b/packages/core/src/http/bull-board.tsindex 3a75ee50a..956e8da13 100644--- a/packages/core/src/http/bull-board.ts+++ b/packages/core/src/http/bull-board.ts@@ -17,11 +17,13 @@import type { Queue as BullQueue } from 'bullmq';import { Elysia } from 'elysia';import type { AppDeps } from '../context';+import { basicAuthChallenge, matchesBasicAuth } from '../shared/basic-auth';import { requestContext } from './context';export const BULL_BOARD_BASE_PATH = '/bullboard';const UNAUTHORIZED = 401;+const BULL_BOARD_REALM = 'OpenPanel ops';/*** Mounted only where the role consumes and `DISABLE_BULLBOARD` is unset@@ -67,13 +69,31 @@ export async function bullBoardRoutes(return new Elysia({ name: 'core/http/bull-board' }).use(requestContext(deps))- .onBeforeHandle({ as: 'global' }, async ({ path, ctx, status }) => {- if (!path.startsWith(BULL_BOARD_BASE_PATH)) {- return;+ .onBeforeHandle(+ { as: 'global' },+ async ({ path, ctx, status, request, set }) => {+ if (!path.startsWith(BULL_BOARD_BASE_PATH)) {+ return;+ }+ // Two gates, both required: a dashboard session proves a human, the+ // operator credentials prove an operator. The queue UI can add, retry+ // and clean jobs, so being any signed-up user is not enough+ // (main #511, GHSA-r627-6vrh-65p9).+ if (!(await ctx.session())) {+ return status(UNAUTHORIZED);+ }+ const admin = ctx.config.adminAuth;+ if (+ admin &&+ !matchesBasicAuth(request.headers.get('authorization'), admin)+ ) {+ set.headers = {+ ...set.headers,+ ...basicAuthChallenge(BULL_BOARD_REALM),+ };+ return status(UNAUTHORIZED);+ }}- if (!(await ctx.session())) {- return status(UNAUTHORIZED);- }- })+ ).use(board) as unknown as Elysia;}diff --git a/packages/core/src/shared/basic-auth.test.ts b/packages/core/src/shared/basic-auth.test.tsnew file mode 100644index 000000000..da5b00ad4--- /dev/null+++ b/packages/core/src/shared/basic-auth.test.ts@@ -0,0 +1,54 @@+// Ported from apps/worker/src/utils/basic-auth.test.ts (main #511).+import { describe, expect, it } from 'bun:test';+import { basicAuthChallenge, matchesBasicAuth } from './basic-auth';++const EXPECTED = { username: 'ops', password: 'hunter2' };++function header(user: string, password: string): string {+ return `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`;+}++describe('matchesBasicAuth', () => {+ it('accepts the exact pair', () => {+ expect(matchesBasicAuth(header('ops', 'hunter2'), EXPECTED)).toBe(true);+ });++ it('accepts a lowercase scheme', () => {+ const value = header('ops', 'hunter2').replace('Basic', 'basic');+ expect(matchesBasicAuth(value, EXPECTED)).toBe(true);+ });++ it('refuses a wrong username or password', () => {+ expect(matchesBasicAuth(header('ops', 'nope'), EXPECTED)).toBe(false);+ expect(matchesBasicAuth(header('nope', 'hunter2'), EXPECTED)).toBe(false);+ });++ it('refuses a missing, malformed or non-basic header', () => {+ expect(matchesBasicAuth(undefined, EXPECTED)).toBe(false);+ expect(matchesBasicAuth(null, EXPECTED)).toBe(false);+ expect(matchesBasicAuth('', EXPECTED)).toBe(false);+ expect(matchesBasicAuth('Basic', EXPECTED)).toBe(false);+ expect(matchesBasicAuth('Bearer token', EXPECTED)).toBe(false);+ expect(+ matchesBasicAuth(+ `Basic ${Buffer.from('no-separator').toString('base64')}`,+ EXPECTED+ )+ ).toBe(false);+ });++ it('keeps a colon in the password', () => {+ expect(+ matchesBasicAuth(header('ops', 'a:b'), {+ username: 'ops',+ password: 'a:b',+ })+ ).toBe(true);+ });++ it('challenges with the realm', () => {+ expect(basicAuthChallenge('OpenPanel ops')).toEqual({+ 'WWW-Authenticate': 'Basic realm="OpenPanel ops"',+ });+ });+});diff --git a/packages/core/src/shared/basic-auth.ts b/packages/core/src/shared/basic-auth.tsnew file mode 100644index 000000000..c4aea88b6--- /dev/null+++ b/packages/core/src/shared/basic-auth.ts@@ -0,0 +1,49 @@+// HTTP Basic auth for operator-only surfaces. Browsers prompt for the+// credentials, so such a surface needs no UI of its own.+//+// Ported from apps/worker/src/utils/basic-auth.ts (main #511) as a plain+// predicate: express middleware has no home here, and the caller decides what+// a refusal looks like on its transport.++import { timingSafeEqual } from 'node:crypto';++export interface BasicAuthCredentials {+ username: string;+ password: string;+}++const BASIC_SCHEME = 'basic';++function safeEqual(a: string, b: string): boolean {+ const left = Buffer.from(a);+ const right = Buffer.from(b);+ // timingSafeEqual throws on a length mismatch, so the length is compared first.+ return left.length === right.length && timingSafeEqual(left, right);+}++/** Whether an `Authorization` header carries exactly these credentials. */+export function matchesBasicAuth(+ header: string | null | undefined,+ expected: BasicAuthCredentials+): boolean {+ const [scheme, encoded] = (header ?? '').split(' ');+ if (scheme?.toLowerCase() !== BASIC_SCHEME || !encoded) {+ return false;+ }++ const decoded = Buffer.from(encoded, 'base64').toString('utf8');+ const separator = decoded.indexOf(':');+ if (separator === -1) {+ return false;+ }++ return (+ safeEqual(decoded.slice(0, separator), expected.username) &&+ safeEqual(decoded.slice(separator + 1), expected.password)+ );+}++/** The header that makes a browser show its credentials prompt. */+export function basicAuthChallenge(realm: string): Record<string, string> {+ return { 'WWW-Authenticate': `Basic realm="${realm}"` };+}diff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.tsindex cd4417359..1475185ce 100644--- a/packages/core/test/config-fixture.ts+++ b/packages/core/test/config-fixture.ts@@ -18,6 +18,7 @@ export function testCoreConfig(dashboardUrl: '',demoUserId: undefined,clickhouseClustered: true,+ adminAuth: undefined,encryptionKey: undefined,pingDisabled: false,logging: {diff --git a/self-hosting/.env.template b/self-hosting/.env.templateindex 67a7c14f4..7754df534 100644--- a/self-hosting/.env.template+++ b/self-hosting/.env.template@@ -12,6 +12,11 @@ DATABASE_URL_DIRECT="$DATABASE_URL_DIRECT"DASHBOARD_URL="$DASHBOARD_URL"API_URL="$API_URL"COOKIE_SECRET="$COOKIE_SECRET"++# HTTP Basic credentials for operator-only surfaces (the queue dashboard at+# /bullboard). Leave empty to guard it with a dashboard session alone.+ADMIN_USERNAME="$ADMIN_USERNAME"+ADMIN_PASSWORD="$ADMIN_PASSWORD"EMAIL_SENDER="$EMAIL_SENDER"RESEND_API_KEY="$RESEND_API_KEY"ENCRYPTION_KEY="$ENCRYPTION_KEY"diff --git a/self-hosting/coolify.yml b/self-hosting/coolify.ymlindex f8f65fa7b..d2f64496e 100644--- a/self-hosting/coolify.yml+++ b/self-hosting/coolify.yml@@ -229,6 +229,10 @@ services:# Must match the API's secret: unsubscribe links in worker emails are# verified by the API, and signing them needs a real secret- COOKIE_SECRET=${SERVICE_BASE64_COOKIESECRET}+ # Operator credentials for the queue dashboard (HTTP Basic, on top of+ # the dashboard session guard)+ - ADMIN_USERNAME=${SERVICE_USER_ADMIN}+ - ADMIN_PASSWORD=${SERVICE_PASSWORD_ADMIN}# Optional: Google Search Console sync needs the Google OAuth client- GOOGLE_CLIENT_ID=${OPENPANEL_GOOGLE_CLIENT_ID}- GOOGLE_CLIENT_SECRET=${OPENPANEL_GOOGLE_CLIENT_SECRET}diff --git a/self-hosting/quiz.ts b/self-hosting/quiz.tsindex f0fa9f2eb..ced6b5b74 100644--- a/self-hosting/quiz.ts+++ b/self-hosting/quiz.ts@@ -21,6 +21,8 @@ let envs = {DATABASE_URL: '',DOMAIN_NAME: '',COOKIE_SECRET: generatePassword(32),+ ADMIN_USERNAME: 'admin',+ ADMIN_PASSWORD: generatePassword(24),// AES-256 key for at-rest encryption (GSC tokens, 2FA secrets). Must be// exactly 32 bytes / 64 hex chars, so it can't reuse generatePassword.ENCRYPTION_KEY: randomBytes(32).toString('hex'),@@ -159,6 +161,8 @@ function writeEnvFile(envs: EnvVars) {const newEnvFile = envTemplate.replace('$COOKIE_SECRET', envs.COOKIE_SECRET)+ .replace('$ADMIN_USERNAME', envs.ADMIN_USERNAME)+ .replace('$ADMIN_PASSWORD', envs.ADMIN_PASSWORD).replace('$ENCRYPTION_KEY', envs.ENCRYPTION_KEY).replace('$CLICKHOUSE_URL', envs.CLICKHOUSE_URL).replace('$REDIS_URL', envs.REDIS_URL)@@ -420,6 +424,8 @@ async function initiateOnboarding() {'postgresql://postgres:postgres@op-db:5432/postgres?schema=public',DOMAIN_NAME: envs.DOMAIN_NAME,COOKIE_SECRET: envs.COOKIE_SECRET,+ ADMIN_USERNAME: envs.ADMIN_USERNAME,+ ADMIN_PASSWORD: envs.ADMIN_PASSWORD,RESEND_API_KEY: envs.RESEND_API_KEY || '',EMAIL_SENDER: envs.EMAIL_SENDER || '',KAFKA_EVENTS_TOPIC_PARTITIONS: envs.KAFKA_EVENTS_TOPIC_PARTITIONS,