Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(security): close the remaining triage advisories (#511)

Carl-Gerhard Lindesvärdf8bb75744d0e
diff --git a/apps/public/content/docs/self-hosting/environment-variables.mdx b/apps/public/content/docs/self-hosting/environment-variables.mdx
index 66b60fc59..798b85c1c 100644
--- a/apps/public/content/docs/self-hosting/environment-variables.mdx
+++ b/apps/public/content/docs/self-hosting/environment-variables.mdx
@@ -703,13 +703,27 @@ Port for the worker service to listen on.
WORKER_PORT=3000
```
+### BULLBOARD_USERNAME / BULLBOARD_PASSWORD
+
+**Type**: `string`
+**Required**: No
+**Default**: None
+
+Credentials for the Bull Board queue dashboard served on the worker port. The dashboard can add, retry and clean jobs, so it is only mounted when both variables are set. Without them the worker logs a warning at startup and serves only `/healthcheck` and `/metrics`. The browser prompts for these credentials (HTTP Basic auth).
+
+**Example**:
+```bash
+BULLBOARD_USERNAME=ops
+BULLBOARD_PASSWORD=$(openssl rand -hex 16)
+```
+
### DISABLE_BULLBOARD
**Type**: `boolean`
**Required**: No
**Default**: `false`
-Disable BullMQ board UI. Set to `true` or `1` to disable the queue monitoring dashboard.
+Disable the Bull Board queue dashboard entirely and silence the startup warning about missing credentials. Set to `true` or `1`.
**Example**:
```bash
diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts
index 0a38bffa2..23eac47f5 100644
--- a/apps/worker/src/index.ts
+++ b/apps/worker/src/index.ts
@@ -24,6 +24,7 @@ import { bootCron } from './boot-cron';
import { bootDebugRoutes } from './boot-debug';
import { bootWorkers } from './boot-workers';
import { register } from './metrics';
+import { basicAuth } from './utils/basic-auth';
import { isShuttingDown } from './utils/graceful-shutdown';
import { logger } from './utils/logger';
import { getEventsHeartbeat } from './utils/worker-heartbeat';
@@ -45,31 +46,6 @@ async function start() {
bootDebugRoutes(app);
}
- if (
- process.env.DISABLE_BULLBOARD !== '1' &&
- process.env.DISABLE_BULLBOARD !== 'true'
- ) {
- const serverAdapter = new ExpressAdapter();
- serverAdapter.setBasePath('/');
- createBullBoard({
- queues: [
- ...eventsGroupQueues.map(
- (queue) => new BullBoardGroupMQAdapter(queue) as any
- ),
- new BullMQAdapter(sessionsQueue),
- new BullMQAdapter(cronQueue),
- new BullMQAdapter(notificationQueue),
- new BullMQAdapter(importQueue),
- new BullMQAdapter(insightsQueue),
- new BullMQAdapter(gscQueue),
- new BullMQAdapter(cohortComputeQueue),
- ],
- serverAdapter,
- });
-
- app.use('/', serverAdapter.getRouter());
- }
-
app.get('/metrics', (req, res) => {
res.set('Content-Type', register.contentType);
register
@@ -127,6 +103,50 @@ async function start() {
failedDependencies,
workingDependencies,
});
+
+ // Bull Board exposes every queue with add/retry/clean enabled, so it never
+ // mounts without credentials (GHSA-r627-6vrh-65p9). /metrics and
+ // /healthcheck are registered above so the auth guard does not cover them.
+ const bullboardDisabled =
+ process.env.DISABLE_BULLBOARD === '1' ||
+ process.env.DISABLE_BULLBOARD === 'true';
+ const bullboardUsername = process.env.BULLBOARD_USERNAME;
+ const bullboardPassword = process.env.BULLBOARD_PASSWORD;
+
+ const hasBullboardCredentials = Boolean(bullboardUsername && bullboardPassword);
+
+ if (!bullboardDisabled && !hasBullboardCredentials) {
+ logger.warn(
+ 'Bull Board is not mounted: set BULLBOARD_USERNAME and BULLBOARD_PASSWORD to enable the queue dashboard, or DISABLE_BULLBOARD=true to silence this warning',
+ );
+ }
+
+ if (!bullboardDisabled && bullboardUsername && bullboardPassword) {
+ const serverAdapter = new ExpressAdapter();
+ serverAdapter.setBasePath('/');
+ createBullBoard({
+ queues: [
+ ...eventsGroupQueues.map(
+ (queue) => new BullBoardGroupMQAdapter(queue) as any
+ ),
+ new BullMQAdapter(sessionsQueue),
+ new BullMQAdapter(cronQueue),
+ new BullMQAdapter(notificationQueue),
+ new BullMQAdapter(importQueue),
+ new BullMQAdapter(insightsQueue),
+ new BullMQAdapter(gscQueue),
+ new BullMQAdapter(cohortComputeQueue),
+ ],
+ serverAdapter,
+ });
+
+ app.use(
+ '/',
+ basicAuth(bullboardUsername, bullboardPassword),
+ serverAdapter.getRouter(),
+ );
+ }
+
});
// Kubernetes liveness — shallow, event loop only.
diff --git a/apps/worker/src/utils/basic-auth.test.ts b/apps/worker/src/utils/basic-auth.test.ts
new file mode 100644
index 000000000..e10a092bd
--- /dev/null
+++ b/apps/worker/src/utils/basic-auth.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it, vi } from 'vitest';
+import { basicAuth } from './basic-auth';
+
+function run(header?: string) {
+ const req = { headers: { authorization: header } } as never;
+ const res = { set: vi.fn(), status: vi.fn().mockReturnThis(), send: vi.fn() };
+ const next = vi.fn();
+ basicAuth('ops', 's3cret')(req, res as never, next);
+ return { res, next };
+}
+
+const encode = (s: string) => `Basic ${Buffer.from(s).toString('base64')}`;
+
+describe('basicAuth', () => {
+ it('lets the right credentials through', () => {
+ const { next, res } = run(encode('ops:s3cret'));
+ expect(next).toHaveBeenCalled();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('rejects a missing header', () => {
+ const { next, res } = run(undefined);
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(401);
+ expect(res.set).toHaveBeenCalledWith('WWW-Authenticate', expect.stringContaining('Basic'));
+ });
+
+ it('rejects a wrong password, wrong user and malformed value', () => {
+ for (const header of [encode('ops:nope'), encode('root:s3cret'), encode('no-colon'), 'Bearer abc']) {
+ const { next, res } = run(header);
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(401);
+ }
+ });
+
+ it('allows a colon inside the password', () => {
+ const req = { headers: { authorization: encode('ops:a:b') } } as never;
+ const res = { set: vi.fn(), status: vi.fn().mockReturnThis(), send: vi.fn() };
+ const next = vi.fn();
+ basicAuth('ops', 'a:b')(req, res as never, next);
+ expect(next).toHaveBeenCalled();
+ });
+});
diff --git a/apps/worker/src/utils/basic-auth.ts b/apps/worker/src/utils/basic-auth.ts
new file mode 100644
index 000000000..b6b2235ac
--- /dev/null
+++ b/apps/worker/src/utils/basic-auth.ts
@@ -0,0 +1,34 @@
+import { timingSafeEqual } from 'node:crypto';
+import type { NextFunction, Request, Response } from 'express';
+
+function safeEqual(a: string, b: string): boolean {
+ const bufA = Buffer.from(a);
+ const bufB = Buffer.from(b);
+ return bufA.length === bufB.length && timingSafeEqual(bufA, bufB);
+}
+
+/**
+ * HTTP Basic auth for operator-only routes such as Bull Board. Browsers
+ * prompt for the credentials, so no extra UI is needed.
+ */
+export function basicAuth(username: string, password: string) {
+ return (req: Request, res: Response, next: NextFunction) => {
+ const [scheme, encoded] = (req.headers.authorization ?? '').split(' ');
+ if (scheme === 'Basic' && encoded) {
+ const decoded = Buffer.from(encoded, 'base64').toString('utf8');
+ const separator = decoded.indexOf(':');
+ const givenUser = decoded.slice(0, separator);
+ const givenPassword = decoded.slice(separator + 1);
+ if (
+ separator !== -1 &&
+ safeEqual(givenUser, username) &&
+ safeEqual(givenPassword, password)
+ ) {
+ next();
+ return;
+ }
+ }
+ res.set('WWW-Authenticate', 'Basic realm="OpenPanel worker"');
+ res.status(401).send('Unauthorized');
+ };
+}
diff --git a/packages/db/code-migrations/migrate.ts b/packages/db/code-migrations/migrate.ts
index 1598f0602..874431d3a 100644
--- a/packages/db/code-migrations/migrate.ts
+++ b/packages/db/code-migrations/migrate.ts
@@ -14,6 +14,38 @@ import {
printBoxMessage,
} from './helpers';
+const CREDENTIAL_QUERY_PARAMS = new Set(['password', 'sslpassword', 'user']);
+
+/**
+ * Connection URLs carry credentials; the startup banner must not put them in
+ * container and CI logs. Keeps scheme, host, port and database, drops the
+ * rest. ClickHouse accepts a comma-separated list, so each URL is handled.
+ */
+function redactConnectionUrls(value: string | undefined): string {
+ if (!value) {
+ return '(not set)';
+ }
+ return value
+ .split(',')
+ .map((raw) => {
+ try {
+ const url = new URL(raw.trim());
+ const params = new URLSearchParams(url.search);
+ for (const key of [...params.keys()]) {
+ if (CREDENTIAL_QUERY_PARAMS.has(key.toLowerCase())) {
+ params.set(key, '***');
+ }
+ }
+ const query = params.toString();
+ const auth = url.username ? '***@' : '';
+ return `${url.protocol}//${auth}${url.host}${url.pathname}${query ? `?${query}` : ''}`;
+ } catch {
+ return '(unparseable url)';
+ }
+ })
+ .join(',');
+}
+
async function migrate() {
const args = process.argv.slice(2);
const migration = args.filter((arg) => !arg.startsWith('--'))[0];
@@ -58,8 +90,8 @@ async function migrate() {
]);
printBoxMessage('🌍 Environment', [
- `POSTGRES: ${process.env.DATABASE_URL}`,
- `CLICKHOUSE: ${process.env.CLICKHOUSE_URL}`,
+ `POSTGRES: ${redactConnectionUrls(process.env.DATABASE_URL)}`,
+ `CLICKHOUSE: ${redactConnectionUrls(process.env.CLICKHOUSE_URL)}`,
]);
if (!getIsSelfHosting()) {
diff --git a/packages/db/src/services/cohort.service.ts b/packages/db/src/services/cohort.service.ts
index 7c72b9c4e..32fe26837 100644
--- a/packages/db/src/services/cohort.service.ts
+++ b/packages/db/src/services/cohort.service.ts
@@ -303,9 +303,22 @@ export function buildEventCriteriaQuery(
`;
}
+/** Columns of the profiles table a cohort filter may reference directly. */
+const PROFILE_FILTER_COLUMNS = new Set([
+ 'id',
+ 'first_name',
+ 'last_name',
+ 'email',
+ 'avatar',
+ 'created_at',
+ 'last_seen_at',
+]);
+
// SQL for a profile filter's column: either a properties Map lookup or a
-// plain column, qualified with the table name.
-function profileColumnAccess(name: string): string {
+// plain column, qualified with the table name. The column name is an
+// identifier and cannot be escaped like a value, so it must come from the
+// allowlist (GHSA-gvwr-5684-wjqc).
+export function profileColumnAccess(name: string): string {
const normalizedName = name.replace(/^profile\./, 'profiles.');
if (normalizedName.startsWith('profiles.properties.')) {
const propKey = normalizedName.replace('profiles.properties.', '');
@@ -313,7 +326,11 @@ function profileColumnAccess(name: string): string {
// user-controlled — a quote in it must not terminate the literal.
return `profiles.properties[${sqlstring.escape(propKey)}]`;
}
- return normalizedName;
+ const column = normalizedName.replace(/^profiles\./, '');
+ if (!PROFILE_FILTER_COLUMNS.has(column)) {
+ throw new Error(`Unknown profile filter column: ${name}`);
+ }
+ return `profiles.${column}`;
}
function buildProfileCohortHavingClause(
diff --git a/packages/db/src/services/conversion.service.ts b/packages/db/src/services/conversion.service.ts
index fc721722d..9637d31e6 100644
--- a/packages/db/src/services/conversion.service.ts
+++ b/packages/db/src/services/conversion.service.ts
@@ -134,12 +134,14 @@ export class ConversionService {
const funnelWindowSeconds = funnelWindow * 3600;
// Build funnel conditions
+ const eventAName = sqlstring.escape(eventA.name);
+ const eventBName = sqlstring.escape(eventB.name);
const conditionA = whereA
- ? `(events.name = '${eventA.name}' AND ${whereA})`
- : `events.name = '${eventA.name}'`;
+ ? `(events.name = ${eventAName} AND ${whereA})`
+ : `events.name = ${eventAName}`;
const conditionB = whereB
- ? `(events.name = '${eventB.name}' AND ${whereB})`
- : `events.name = '${eventB.name}'`;
+ ? `(events.name = ${eventBName} AND ${whereB})`
+ : `events.name = ${eventBName}`;
const groupJoin = needsGroupArrayJoin
? `ARRAY JOIN groups AS _group_id LEFT ANY JOIN (SELECT id, name, type, properties FROM ${TABLE_NAMES.groups} FINAL WHERE project_id = ${sqlstring.escape(projectId)}) AS _g ON _g.id = _group_id`
@@ -175,9 +177,9 @@ export class ConversionService {
${profileJoin}
${groupJoin}
${cohortJoinsSql}
- WHERE project_id = '${projectId}'
- AND events.name IN ('${eventA.name}', '${eventB.name}')
- AND created_at BETWEEN toDateTime('${startDate}') AND toDateTime('${endDate}')
+ WHERE project_id = ${sqlstring.escape(projectId)}
+ AND events.name IN (${eventAName}, ${eventBName})
+ AND created_at BETWEEN toDateTime(${sqlstring.escape(startDate)}) AND toDateTime(${sqlstring.escape(endDate)})
GROUP BY ${group}${breakdownExpressions.length ? `, ${breakdownExpressions.join(', ')}` : ''})
`),
)
diff --git a/packages/db/src/services/sankey.service.ts b/packages/db/src/services/sankey.service.ts
index af1844612..ee0df68eb 100644
--- a/packages/db/src/services/sankey.service.ts
+++ b/packages/db/src/services/sankey.service.ts
@@ -1,5 +1,6 @@
import { chartColors } from '@openpanel/constants';
import { type IChartEventFilter, zChartEvent } from '@openpanel/validation';
+import sqlstring from 'sqlstring';
import { z } from 'zod';
import { TABLE_NAMES, ch } from '../clickhouse/client';
import { clix } from '../clickhouse/query-builder';
@@ -58,13 +59,13 @@ export class SankeyService {
if (include && include.length > 0) {
const eventNames = [...include, startEventName, endEventName]
.filter((item) => item !== undefined)
- .map((e) => `'${e!.replace(/'/g, "''")}'`)
+ .map((e) => sqlstring.escape(e))
.join(', ');
return `name IN (${eventNames})`;
}
if (exclude.length > 0) {
const excludedNames = exclude
- .map((e) => `'${e.replace(/'/g, "''")}'`)
+ .map((e) => sqlstring.escape(e))
.join(', ');
return `name NOT IN (${excludedNames})`;
}
@@ -102,40 +103,40 @@ export class SankeyService {
const defaultSliceExpr = `arraySlice(events_deduped, 1, ${steps})`;
if (mode === 'after' && startEvent) {
- const escapedStartEvent = startEvent.name.replace(/'/g, "''");
+ const escapedStartEvent = sqlstring.escape(startEvent.name);
const sessionFilter = hasStartEventCTE
? 'session_id IN (SELECT session_id FROM start_event_sessions)'
- : `arrayExists(x -> x = '${escapedStartEvent}', events_deduped)`;
- const eventsSliceExpr = `arraySlice(events_deduped, arrayFirstIndex(x -> x = '${escapedStartEvent}', events_deduped), ${steps})`;
+ : `arrayExists(x -> x = ${escapedStartEvent}, events_deduped)`;
+ const eventsSliceExpr = `arraySlice(events_deduped, arrayFirstIndex(x -> x = ${escapedStartEvent}, events_deduped), ${steps})`;
return { sessionFilter, eventsSliceExpr };
}
if (mode === 'before' && startEvent) {
- const escapedStartEvent = startEvent.name.replace(/'/g, "''");
+ const escapedStartEvent = sqlstring.escape(startEvent.name);
const sessionFilter = hasStartEventCTE
? 'session_id IN (SELECT session_id FROM start_event_sessions)'
- : `arrayExists(x -> x = '${escapedStartEvent}', events_deduped)`;
+ : `arrayExists(x -> x = ${escapedStartEvent}, events_deduped)`;
const eventsSliceExpr = `arraySlice(
events_deduped,
- greatest(1, arrayFirstIndex(x -> x = '${escapedStartEvent}', events_deduped) - ${steps} + 1),
- arrayFirstIndex(x -> x = '${escapedStartEvent}', events_deduped) - greatest(1, arrayFirstIndex(x -> x = '${escapedStartEvent}', events_deduped) - ${steps} + 1) + 1
+ greatest(1, arrayFirstIndex(x -> x = ${escapedStartEvent}, events_deduped) - ${steps} + 1),
+ arrayFirstIndex(x -> x = ${escapedStartEvent}, events_deduped) - greatest(1, arrayFirstIndex(x -> x = ${escapedStartEvent}, events_deduped) - ${steps} + 1) + 1
)`;
return { sessionFilter, eventsSliceExpr };
}
if (mode === 'between' && startEvent && endEvent) {
- const escapedStartEvent = startEvent.name.replace(/'/g, "''");
- const escapedEndEvent = endEvent.name.replace(/'/g, "''");
+ const escapedStartEvent = sqlstring.escape(startEvent.name);
+ const escapedEndEvent = sqlstring.escape(endEvent.name);
let sessionFilter = '';
if (hasStartEventCTE && hasEndEventCTE) {
sessionFilter =
'session_id IN (SELECT session_id FROM start_event_sessions) AND session_id IN (SELECT session_id FROM end_event_sessions)';
} else if (hasStartEventCTE) {
- sessionFilter = `session_id IN (SELECT session_id FROM start_event_sessions) AND arrayExists(x -> x = '${escapedEndEvent}', events_deduped)`;
+ sessionFilter = `session_id IN (SELECT session_id FROM start_event_sessions) AND arrayExists(x -> x = ${escapedEndEvent}, events_deduped)`;
} else if (hasEndEventCTE) {
- sessionFilter = `arrayExists(x -> x = '${escapedStartEvent}', events_deduped) AND session_id IN (SELECT session_id FROM end_event_sessions)`;
+ sessionFilter = `arrayExists(x -> x = ${escapedStartEvent}, events_deduped) AND session_id IN (SELECT session_id FROM end_event_sessions)`;
} else {
- sessionFilter = `arrayExists(x -> x = '${escapedStartEvent}', events_deduped) AND arrayExists(x -> x = '${escapedEndEvent}', events_deduped)`;
+ sessionFilter = `arrayExists(x -> x = ${escapedStartEvent}, events_deduped) AND arrayExists(x -> x = ${escapedEndEvent}, events_deduped)`;
}
return { sessionFilter, eventsSliceExpr: defaultSliceExpr };
}
@@ -172,8 +173,8 @@ export class SankeyService {
}>([
'session_id',
'events',
- `arrayFirstIndex(x -> x = '${startEvent.name.replace(/'/g, "''")}', events) as start_index`,
- `arrayFirstIndex(x -> x = '${endEvent.name.replace(/'/g, "''")}', events) as end_index`,
+ `arrayFirstIndex(x -> x = ${sqlstring.escape(startEvent.name)}, events) as start_index`,
+ `arrayFirstIndex(x -> x = ${sqlstring.escape(endEvent.name)}, events) as end_index`,
])
.from('session_paths')
.having('start_index', '>', 0)
diff --git a/packages/db/src/services/share.service.ts b/packages/db/src/services/share.service.ts
index 3a53f399c..f6ba3b6eb 100644
--- a/packages/db/src/services/share.service.ts
+++ b/packages/db/src/services/share.service.ts
@@ -3,6 +3,57 @@ import { hasShareAccess } from '@openpanel/common/server/share-access';
import { db } from '../prisma-client';
import { getProjectAccess } from './access.service';
+export type ShareKind = 'overview' | 'dashboard' | 'report';
+
+/**
+ * Whether an anonymous viewer may read project-scoped side data (chart
+ * annotations, bot events) for a project.
+ *
+ * The viewer is allowed only if the project has at least one share of the
+ * given kinds that is public and, when password-protected, has been unlocked
+ * with a verified cookie. A share row merely existing is not enough: shares
+ * are toggled off by setting `public: false` (the row stays), and a password
+ * share must not leak through a side endpoint that the share page itself
+ * would refuse.
+ */
+export async function hasAnonymousShareAccessToProject(
+ projectId: string,
+ cookies: Record<string, string | undefined> | undefined,
+ kinds: ShareKind[] = ['overview', 'dashboard', 'report'],
+): Promise<boolean> {
+ const select = { id: true, password: true } as const;
+ const where = { projectId, public: true } as const;
+
+ const [overviews, dashboards, reports] = await Promise.all([
+ kinds.includes('overview')
+ ? db.shareOverview.findMany({ where, select })
+ : [],
+ kinds.includes('dashboard')
+ ? db.shareDashboard.findMany({ where, select })
+ : [],
+ kinds.includes('report')
+ ? db.shareReport.findMany({ where, select })
+ : [],
+ ]);
+
+ const candidates: { type: ShareKind; id: string; password: string | null }[] =
+ [
+ ...overviews.map((s) => ({ type: 'overview' as const, ...s })),
+ ...dashboards.map((s) => ({ type: 'dashboard' as const, ...s })),
+ ...reports.map((s) => ({ type: 'report' as const, ...s })),
+ ];
+
+ return candidates.some(
+ (share) =>
+ !share.password ||
+ hasShareAccess(cookies, {
+ type: share.type,
+ id: share.id,
+ passwordHash: share.password,
+ }),
+ );
+}
+
export function getShareOverviewById(id: string) {
return db.shareOverview.findFirst({
where: {
diff --git a/packages/email/src/index.tsx b/packages/email/src/index.tsx
index d27437dab..89d5e47de 100644
--- a/packages/email/src/index.tsx
+++ b/packages/email/src/index.tsx
@@ -8,6 +8,15 @@ import { db } from '@openpanel/db';
import { type TemplateKey, type Templates, templates } from './emails';
import { getUnsubscribeUrl } from './unsubscribe';
+/** a***@example.com, enough to correlate a log line without exposing the address. */
+function redactEmail(email: string): string {
+ const at = email.indexOf('@');
+ if (at <= 0) {
+ return '***';
+ }
+ return `${email[0]}***${email.slice(at)}`;
+}
+
export * from './unsubscribe';
const FROM = process.env.EMAIL_SENDER ?? '[email protected]';
@@ -95,11 +104,12 @@ export async function sendEmail<T extends TemplateKey>(
}
if (!process.env.RESEND_API_KEY) {
- console.log('No SMTP_HOST or RESEND_API_KEY found, here is the data');
- console.log('Template:', template);
- console.log('Subject: ', subject);
- console.log('To: ', to);
- console.log('Data: ', JSON.stringify(data, null, 2));
+ // Never dump the payload: template data carries password-reset and
+ // unsubscribe links, and the recipient is personal data
+ // (GHSA-xr2x-w49w-hp2c).
+ console.warn(
+ `Email not sent (email_provider_not_configured): template=${templateKey} to=${redactEmail(to)}`,
+ );
return null;
}
diff --git a/packages/email/src/unsubscribe.ts b/packages/email/src/unsubscribe.ts
index 1a6ced129..7a09323e2 100644
--- a/packages/email/src/unsubscribe.ts
+++ b/packages/email/src/unsubscribe.ts
@@ -1,14 +1,23 @@
import { createHmac, timingSafeEqual } from 'crypto';
-const SECRET =
- process.env.UNSUBSCRIBE_SECRET ||
- process.env.COOKIE_SECRET ||
- process.env.SECRET ||
- 'default-secret-change-in-production';
+/**
+ * Read at call time, not import time, so a missing secret fails the one
+ * request that needs it with a clear message instead of silently signing
+ * with a well-known default that anyone could forge.
+ */
+function getSecret(): string {
+ const secret = process.env.UNSUBSCRIBE_SECRET || process.env.COOKIE_SECRET;
+ if (!secret) {
+ throw new Error(
+ 'UNSUBSCRIBE_SECRET or COOKIE_SECRET must be set to sign unsubscribe links',
+ );
+ }
+ return secret;
+}
export function generateUnsubscribeToken(email: string, category: string): string {
const data = `${email}:${category}`;
- return createHmac('sha256', SECRET).update(data).digest('hex');
+ return createHmac('sha256', getSecret()).update(data).digest('hex');
}
export function verifyUnsubscribeToken(
diff --git a/packages/trpc/src/routers/event.ts b/packages/trpc/src/routers/event.ts
index 018b8aaf4..0177061e7 100644
--- a/packages/trpc/src/routers/event.ts
+++ b/packages/trpc/src/routers/event.ts
@@ -3,9 +3,6 @@ import sqlstring from 'sqlstring';
import { z } from 'zod';
import {
- type IServiceProfile,
- type IServiceSession,
- TABLE_NAMES,
chQuery,
convertClickhouseDateToJs,
db,
@@ -15,8 +12,12 @@ import {
getEventList,
getEventMetasCached,
getSettingsForProject,
+ hasAnonymousShareAccessToProject,
pagesService,
sessionService,
+ TABLE_NAMES,
+ type IServiceProfile,
+ type IServiceSession,
} from '@openpanel/db';
import {
zChartEventFilter,
@@ -290,13 +291,14 @@ export const eventRouter = createTRPCRouter({
throw new TRPCForbiddenError('You do not have access to this project');
}
} else {
- const share = await db.shareOverview.findFirst({
- where: {
- projectId,
- },
- });
-
- if (!share) {
+ // Anonymous callers only see bot events through an unlocked public
+ // overview share; the row existing is not enough (GHSA-r4g5-vgpj-923m).
+ const allowed = await hasAnonymousShareAccessToProject(
+ projectId,
+ ctx.cookies,
+ ['overview'],
+ );
+ if (!allowed) {
throw new TRPCForbiddenError('You do not have access to this project');
}
}
diff --git a/packages/trpc/src/routers/reference.test.ts b/packages/trpc/src/routers/reference.test.ts
new file mode 100644
index 000000000..607292493
--- /dev/null
+++ b/packages/trpc/src/routers/reference.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { referenceFindMany, hasAnonymousShareAccessToProject, getProjectAccess } =
+ vi.hoisted(() => ({
+ referenceFindMany: vi.fn(),
+ hasAnonymousShareAccessToProject: vi.fn(),
+ getProjectAccess: vi.fn(),
+ }));
+
+vi.mock('@openpanel/db', () => ({
+ db: { reference: { findMany: referenceFindMany } },
+ getChartStartEndDate: () => ({
+ startDate: '2024-01-01T00:00:00.000Z',
+ endDate: '2024-02-01T00:00:00.000Z',
+ }),
+ getSettingsForProject: vi.fn().mockResolvedValue({ timezone: 'UTC' }),
+ hasAnonymousShareAccessToProject,
+ getProjectAccess,
+ getOrganizationAccess: vi.fn(),
+ getClientAccess: vi.fn(),
+ canWriteProject: vi.fn(),
+ runWithAlsSession: (_id: unknown, fn: () => unknown) => fn(),
+}));
+
+import { referenceRouter } from './reference';
+
+// An unauthenticated request carries an empty session, not a missing one.
+const caller = (session: { userId: string | null }, cookies = {}) =>
+ referenceRouter.createCaller({
+ req: { log: { info: vi.fn(), error: vi.fn() } },
+ res: {},
+ session,
+ setCookie: vi.fn(),
+ cookies,
+ } as never);
+
+const input = {
+ projectId: 'victim-project',
+ range: '30d' as const,
+ startDate: null,
+ endDate: null,
+};
+
+describe('reference.getChartReferences (GHSA-vrrm-p9p4-2gfg)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ referenceFindMany.mockResolvedValue([{ title: 'Deploy v2' }]);
+ });
+
+ it('refuses an anonymous caller when the project has no unlocked share', async () => {
+ hasAnonymousShareAccessToProject.mockResolvedValue(false);
+ await expect(caller({ userId: null }).getChartReferences(input)).rejects.toThrow(
+ 'do not have access',
+ );
+ expect(referenceFindMany).not.toHaveBeenCalled();
+ });
+
+ it('serves an anonymous caller who holds an unlocked public share', async () => {
+ hasAnonymousShareAccessToProject.mockResolvedValue(true);
+ const cookies = { 'shared-overview-abc': 'token' };
+ const res = await caller({ userId: null }, cookies).getChartReferences(input);
+ expect(res).toEqual([{ title: 'Deploy v2' }]);
+ expect(hasAnonymousShareAccessToProject).toHaveBeenCalledWith(
+ 'victim-project',
+ cookies,
+ );
+ });
+
+ it('refuses a member without access to the project', async () => {
+ getProjectAccess.mockResolvedValue(null);
+ await expect(
+ caller({ userId: 'u1' }).getChartReferences(input),
+ ).rejects.toThrow('do not have access');
+ expect(hasAnonymousShareAccessToProject).not.toHaveBeenCalled();
+ });
+
+ it('serves a member with access', async () => {
+ getProjectAccess.mockResolvedValue({ level: 'read' });
+ const res = await caller({ userId: 'u1' }).getChartReferences(input);
+ expect(res).toEqual([{ title: 'Deploy v2' }]);
+ });
+});
diff --git a/packages/trpc/src/routers/reference.ts b/packages/trpc/src/routers/reference.ts
index 8f208a3cf..4a61f4908 100644
--- a/packages/trpc/src/routers/reference.ts
+++ b/packages/trpc/src/routers/reference.ts
@@ -1,6 +1,11 @@
import { z } from 'zod';
-import { db, getChartStartEndDate, getSettingsForProject } from '@openpanel/db';
+import {
+ db,
+ getChartStartEndDate,
+ getSettingsForProject,
+ hasAnonymousShareAccessToProject,
+} from '@openpanel/db';
import { zCreateReference, zRange } from '@openpanel/validation';
import { getProjectAccess, requireProjectAccess } from '../access';
@@ -107,7 +112,29 @@ export const referenceRouter = createTRPCRouter({
range: zRange,
}),
)
- .query(async ({ input: { projectId, ...input } }) => {
+ .query(async ({ input: { projectId, ...input }, ctx }) => {
+ // Public so that share pages can draw annotations on their charts, but
+ // never without a check: a member needs project access, an anonymous
+ // viewer needs an unlocked public share for the project
+ // (GHSA-vrrm-p9p4-2gfg).
+ if (ctx.session.userId) {
+ const access = await getProjectAccess({
+ userId: ctx.session.userId,
+ projectId,
+ });
+ if (!access) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+ } else {
+ const allowed = await hasAnonymousShareAccessToProject(
+ projectId,
+ ctx.cookies,
+ );
+ if (!allowed) {
+ throw new TRPCForbiddenError('You do not have access to this project');
+ }
+ }
+
const { timezone } = await getSettingsForProject(projectId);
const { startDate, endDate } = getChartStartEndDate(input, timezone);
return db.reference.findMany({
diff --git a/self-hosting/coolify.yml b/self-hosting/coolify.yml
index aeef6b301..49ca43e87 100644
--- a/self-hosting/coolify.yml
+++ b/self-hosting/coolify.yml
@@ -205,9 +205,14 @@ services:
environment:
# FQDN
- SERVICE_FQDN_OPBULLBOARD
+ # Bull Board is only served with credentials (HTTP Basic auth)
+ - BULLBOARD_USERNAME=${SERVICE_USER_BULLBOARD}
+ - BULLBOARD_PASSWORD=${SERVICE_PASSWORD_BULLBOARD}
# Common
- NODE_ENV=production
- SELF_HOSTED=true
+ # Must match the API's secret: unsubscribe links in worker emails are verified by the API
+ - COOKIE_SECRET=${SERVICE_BASE64_COOKIESECRET}
# URLs
- DATABASE_URL=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public
- DATABASE_URL_DIRECT=postgres://${SERVICE_USER_POSTGRES}:${SERVICE_PASSWORD_POSTGRES}@opdb:5432/${OPENPANEL_POSTGRES_DB:-openpanel-db}?schema=public