🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance analytics API security and validation
Bill Yang7fd1e41bb1d5
diff --git a/server/src/api/analytics/getJourneys.ts b/server/src/api/analytics/getJourneys.tsindex 97efc086a..919ee85f3 100644--- a/server/src/api/analytics/getJourneys.ts+++ b/server/src/api/analytics/getJourneys.ts@@ -1,9 +1,19 @@import { FilterParams } from "@rybbit/shared";import { FastifyReply, FastifyRequest } from "fastify";+import SqlString from "sqlstring";+import { z } from "zod";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getFilterStatement } from "./utils/getFilterStatement.js";import { getTimeStatement, patternToRegex } from "./utils/utils.js";+// stepFilters arrives as a JSON object mapping a (numeric) step index to a path+// pattern. Both the keys and values are attacker-controlled, so validate the+// shape before interpolating any of it into the ClickHouse query.+const stepFiltersSchema = z.record(+ z.string().regex(/^\d+$/, "Step index must be a non-negative integer"),+ z.string().max(2048)+);+export const getJourneys = async (request: FastifyRequest<{Params: { siteId: string };@@ -38,11 +48,11 @@ export const getJourneys = async (const timeStatement = getTimeStatement(request.query);const filterStatement = getFilterStatement(filters, Number(siteId), timeStatement);- // Parse step filters- let parsedStepFilters: Record<number, string> = {};+ // Parse and validate step filters+ let parsedStepFilters: Record<string, string> = {};if (stepFilters) {try {- parsedStepFilters = JSON.parse(stepFilters);+ parsedStepFilters = stepFiltersSchema.parse(JSON.parse(stepFilters));} catch (error) {return reply.status(400).send({error: "Invalid stepFilters format",@@ -56,12 +66,13 @@ export const getJourneys = async (.map(([step, path]) => {const stepIndex = parseInt(step, 10) + 1; // ClickHouse arrays are 1-indexedif (path.includes("*")) {- // Use regex matching for wildcard patterns+ // Use regex matching for wildcard patterns. SqlString.escape correctly+ // escapes the regex literal for ClickHouse (handles both ' and \).const regex = patternToRegex(path);- return `match(journey[${stepIndex}], '${regex.replace(/'/g, "\\'")}')`;+ return `match(journey[${stepIndex}], ${SqlString.escape(regex)})`;}// Use exact match for non-wildcard patterns (more efficient)- return `journey[${stepIndex}] = '${path.replace(/'/g, "''")}'`;+ return `journey[${stepIndex}] = ${SqlString.escape(path)}`;}).join(" AND ");diff --git a/server/src/api/analytics/utils/getFilterStatement.ts b/server/src/api/analytics/utils/getFilterStatement.tsindex 97b1c883c..fc5aefb23 100644--- a/server/src/api/analytics/utils/getFilterStatement.ts+++ b/server/src/api/analytics/utils/getFilterStatement.ts@@ -58,16 +58,18 @@ export const getSqlParam = (parameter: FilterParameter) => {return `feature_flags[${SqlString.escape(key)}]`;}- // Handle URL parameters through the url_parameters map+ // Handle URL parameters through the url_parameters map.+ // The map key is attacker-controlled, so it must be escaped (matching the+ // feature_flag branch above) — not raw-interpolated — to prevent SQL injection.if (parameter.startsWith("utm_") || parameter.startsWith("url_param:")) {// For explicit url_param: prefix (e.g., url_param:campaign_id)if (parameter.startsWith("url_param:")) {const paramName = parameter.substring("url_param:".length);- return `url_parameters['${paramName}']`;+ return `url_parameters[${SqlString.escape(paramName)}]`;}const utm = parameter; // e.g., utm_source, utm_medium, etc.- return `url_parameters['${utm}']`;+ return `url_parameters[${SqlString.escape(utm)}]`;}if (parameter === "referrer") {diff --git a/server/src/api/gsc/callback.ts b/server/src/api/gsc/callback.tsindex f465f46df..58a4ebdf0 100644--- a/server/src/api/gsc/callback.ts+++ b/server/src/api/gsc/callback.ts@@ -2,8 +2,8 @@ import { FastifyReply, FastifyRequest } from "fastify";import { GSCCallbackRequest } from "./types.js";import { gscConnections } from "../../db/postgres/schema.js";import { eq } from "drizzle-orm";-import { getGSCProperties } from "./utils.js";-import { getSessionFromReq } from "../../lib/auth-utils.js";+import { getGSCProperties, verifyGSCState } from "./utils.js";+import { getSessionFromReq, getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";import { db } from "../../db/postgres/postgres.js";import { logger } from "../../lib/logger/logger.js";@@ -25,18 +25,20 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:if (error) {logger.info(`OAuth cancelled or failed: ${error}`);- const siteId = state;- return res.redirect(`${process.env.BASE_URL}/${siteId}/main`);+ return res.redirect(`${process.env.BASE_URL}`);}if (!code || !state) {return res.status(400).send({ error: "Missing code or state parameter" });}- const siteId = Number(state);- if (isNaN(siteId)) {- return res.status(400).send({ error: "Invalid site ID in state" });+ // Verify the signed state: this is the only trustworthy source of the target+ // siteId. A tampered/forged/expired state is rejected.+ const statePayload = verifyGSCState(state);+ if (!statePayload) {+ return res.status(400).send({ error: "Invalid or expired state parameter" });}+ const { siteId } = statePayload;// Get session to retrieve userIdconst session = await getSessionFromReq(req);@@ -44,6 +46,19 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:return res.status(401).send({ error: "Unauthorized" });}+ // The session completing the callback must be the same user that initiated+ // the flow (defends against connection fixation / cross-user state reuse).+ if (session.user.id !== statePayload.userId) {+ return res.status(403).send({ error: "State does not match session" });+ }++ // Verify the caller actually has admin access to the target site before+ // writing OAuth tokens against it (prevents IDOR / connection hijack).+ const hasAccess = await getUserHasAdminAccessToSite(req, siteId);+ if (!hasAccess) {+ return res.status(403).send({ error: "Access denied" });+ }+const clientId = process.env.GOOGLE_CLIENT_ID;const clientSecret = process.env.GOOGLE_CLIENT_SECRET;const redirectUri = process.env.GOOGLE_REDIRECT_URI || `${process.env.SERVER_URL}/api/gsc/callback`;diff --git a/server/src/api/gsc/connect.ts b/server/src/api/gsc/connect.tsindex 914663154..65eed4bca 100644--- a/server/src/api/gsc/connect.ts+++ b/server/src/api/gsc/connect.ts@@ -1,7 +1,8 @@import { FastifyReply, FastifyRequest } from "fastify";import { ConnectGSCRequest } from "./types.js";-import { getUserHasAccessToSite } from "../../lib/auth-utils.js";+import { getSessionFromReq, getUserHasAccessToSite } from "../../lib/auth-utils.js";import { logger } from "../../lib/logger/logger.js";+import { signGSCState } from "./utils.js";/*** Initiates the OAuth flow for Google Search Console@@ -22,6 +23,11 @@ export async function connectGSC(req: FastifyRequest<ConnectGSCRequest>, res: Fareturn res.status(403).send({ error: "Access denied" });}+ const session = await getSessionFromReq(req);+ if (!session) {+ return res.status(401).send({ error: "Unauthorized" });+ }+const clientId = process.env.GOOGLE_CLIENT_ID;const redirectUri = process.env.GOOGLE_REDIRECT_URI || `${process.env.SERVER_URL}/api/gsc/callback`;@@ -31,7 +37,9 @@ export async function connectGSC(req: FastifyRequest<ConnectGSCRequest>, res: Fa// Build OAuth URLconst scope = "https://www.googleapis.com/auth/webmasters.readonly";- const state = numericSiteId.toString(); // Pass siteId in state to retrieve after OAuth+ // Signed state binds the flow to this user + site so the callback can't be+ // tricked into binding tokens to a site the caller doesn't control.+ const state = signGSCState(numericSiteId, session.user.id);const authUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");authUrl.searchParams.set("client_id", clientId);diff --git a/server/src/api/gsc/utils.ts b/server/src/api/gsc/utils.tsindex 4fba02f32..16832305e 100644--- a/server/src/api/gsc/utils.ts+++ b/server/src/api/gsc/utils.ts@@ -1,7 +1,71 @@+import crypto from "crypto";import { db } from "../../db/postgres/postgres.js";import { gscConnections } from "../../db/postgres/schema.js";import { eq } from "drizzle-orm";import { logger } from "../../lib/logger/logger.js";+import { SECRET } from "../../lib/const.js";++// How long a signed OAuth state remains valid (15 minutes).+const GSC_STATE_TTL_MS = 15 * 60 * 1000;++interface GSCStatePayload {+ siteId: number;+ userId: string;+ ts: number;+}++function gscStateSecret(): string {+ if (!SECRET) {+ throw new Error("BETTER_AUTH_SECRET is not set; cannot sign GSC OAuth state");+ }+ return SECRET;+}++/**+ * Create a signed, tamper-proof OAuth `state` value binding the flow to the+ * initiating user and the target site. Prevents the callback from trusting an+ * attacker-supplied siteId (IDOR) and mitigates OAuth CSRF / connection fixation.+ */+export function signGSCState(siteId: number, userId: string): string {+ const payload: GSCStatePayload = { siteId, userId, ts: Date.now() };+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");+ const signature = crypto.createHmac("sha256", gscStateSecret()).update(body).digest("base64url");+ return `${body}.${signature}`;+}++/**+ * Verify a signed OAuth `state` value. Returns the decoded payload if the+ * signature is valid and not expired, otherwise null.+ */+export function verifyGSCState(state: string): GSCStatePayload | null {+ const parts = state.split(".");+ if (parts.length !== 2) {+ return null;+ }+ const [body, signature] = parts;++ const expected = crypto.createHmac("sha256", gscStateSecret()).update(body).digest("base64url");+ const sigBuf = Buffer.from(signature);+ const expectedBuf = Buffer.from(expected);+ if (sigBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(sigBuf, expectedBuf)) {+ return null;+ }++ try {+ const payload = JSON.parse(Buffer.from(body, "base64url").toString()) as GSCStatePayload;+ if (+ typeof payload.siteId !== "number" ||+ typeof payload.userId !== "string" ||+ typeof payload.ts !== "number" ||+ Date.now() - payload.ts > GSC_STATE_TTL_MS+ ) {+ return null;+ }+ return payload;+ } catch {+ return null;+ }+}interface GSCTokens {access_token: string;