🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance SQL query handling in analytics API for improved security and maintainability
Bill Yang229df3982c0b
diff --git a/server/src/api/analytics/getLiveSessionLocations.ts b/server/src/api/analytics/getLiveSessionLocations.tsindex 2da7780a2..720fc11df 100644--- a/server/src/api/analytics/getLiveSessionLocations.ts+++ b/server/src/api/analytics/getLiveSessionLocations.ts@@ -1,6 +1,7 @@import { FastifyRequest, FastifyReply } from "fastify";import clickhouse from "../../db/clickhouse/clickhouse.js";import { processResults } from "./utils.js";+import SqlString from "sqlstring";export async function getLiveSessionLocations(req: FastifyRequest<{@@ -30,7 +31,9 @@ WITH stuff AS (eventsWHEREsite_id = {site:Int32}- AND timestamp > now() - interval '${req.query.time} minute'+ AND timestamp > now() - interval ${SqlString.escape(+ Number(req.query.time)+ )} minuteGROUP BYsession_id)diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.tsindex fe53dd639..2f3c88f99 100644--- a/server/src/api/analytics/getOverviewBucketed.ts+++ b/server/src/api/analytics/getOverviewBucketed.ts@@ -5,6 +5,7 @@ import {getTimeStatement,processResults,} from "./utils.js";+import SqlString from "sqlstring";import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";import { validateTimeStatementFillParams } from "./query-validation.js";@@ -50,20 +51,32 @@ function getTimeStatementFill(if (params.date) {const { startDate, endDate, timezone } = params.date;return `WITH FILL FROM toTimeZone(- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime('${startDate}', '${timezone}'))),+ toDateTime(${+ TimeBucketToFn[validatedBucket]+ }(toDateTime(${SqlString.escape(startDate)}, ${SqlString.escape(+ timezone+ )}))),'UTC')TO if(- toDate('${endDate}') = toDate(now(), '${timezone}'),+ toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(+ timezone+ )}),now(),toTimeZone(- toDateTime(${TimeBucketToFn[validatedBucket]}(toDateTime('${endDate}', '${timezone}'))) + INTERVAL 1 DAY,+ toDateTime(${+ TimeBucketToFn[validatedBucket]+ }(toDateTime(${SqlString.escape(endDate)}, ${SqlString.escape(+ timezone+ )}))) + INTERVAL 1 DAY,'UTC')) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;}if (params.pastMinutes) {- return `WITH FILL FROM now() - INTERVAL ${params.pastMinutes} MINUTE TO now() STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;+ return `WITH FILL FROM now() - INTERVAL ${SqlString.escape(+ params.pastMinutes+ )} MINUTE TO now() STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;}return "";}@@ -103,7 +116,7 @@ FROMSELECTtoDateTime(${TimeBucketToFn[bucket]- }(toTimeZone(start_time, '${timezone}'))) AS time,+ }(toTimeZone(start_time, ${SqlString.escape(timezone)}))) AS time,COUNT() AS sessions,AVG(pages_in_session) AS pages_per_session,sumIf(1, pages_in_session = 1) / COUNT() AS bounce_rate,@@ -146,7 +159,7 @@ FULL JOINSELECTtoDateTime(${TimeBucketToFn[bucket]- }(toTimeZone(timestamp, '${timezone}'))) AS time,+ }(toTimeZone(timestamp, ${SqlString.escape(timezone)}))) AS time,COUNT(*) AS pageviews,COUNT(DISTINCT user_id) AS usersFROM eventsdiff --git a/server/src/api/analytics/getSingleCol.ts b/server/src/api/analytics/getSingleCol.tsindex a2f6ee07f..7095280ea 100644--- a/server/src/api/analytics/getSingleCol.ts+++ b/server/src/api/analytics/getSingleCol.ts@@ -8,6 +8,7 @@ import {} from "./utils.js";import { getUserHasAccessToSitePublic } from "../../lib/auth-utils.js";import { FilterParameter } from "./types.js";+import SqlString from "sqlstring";interface GenericRequest {Params: {@@ -48,7 +49,17 @@ const getQuery = (request: FastifyRequest<GenericRequest>) => {});- const limitStatement = limit ? `LIMIT ${Number(limit)}` : "";+ // Validate and sanitize the limit parameter+ let validatedLimit: number | null = null;+ if (limit !== undefined) {+ const parsedLimit = parseInt(String(limit), 10);+ if (!isNaN(parsedLimit) && parsedLimit > 0) {+ validatedLimit = parsedLimit;+ }+ }+ const limitStatement = validatedLimit+ ? `LIMIT ${validatedLimit}`+ : "LIMIT 100"; // Default limitconst percentageStatement = `ROUND(COUNT(distinct(session_id)) * 100.0 / SUM(COUNT(distinct(session_id))) OVER (),