Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .server-changes/fix-realtime-tags-sql-injection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
area: webapp
type: fix
---

Escape single quotes in user-supplied realtime `tags` filter to prevent SQL injection into the Electric `where` clause
10 changes: 9 additions & 1 deletion apps/webapp/app/services/realtimeClient.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ const DEFAULT_ELECTRIC_COLUMNS = [
const RESERVED_COLUMNS = ["id", "taskIdentifier", "friendlyId", "status", "createdAt"];
const RESERVED_SEARCH_PARAMS = ["createdAt", "tags", "skipColumns"];

// Doubles single quotes so a value is safe inside a single-quoted SQL string literal.
export function escapeSqlStringLiteral(value: string): string {
return value.replace(/'/g, "''");
}

export type RealtimeClientOptions = {
electricOrigin: string | string[];
redis: RedisWithClusterOptions;
Expand Down Expand Up @@ -171,7 +176,10 @@ export class RealtimeClient {
const whereClauses: string[] = [`"runtimeEnvironmentId"='${environment.id}'`];

if (params.tags) {
whereClauses.push(`"runTags" @> ARRAY[${params.tags.map((t) => `'${t}'`).join(",")}]`);
// Escape user-supplied tags so they can't break out of the SQL string literal.
whereClauses.push(
`"runTags" @> ARRAY[${params.tags.map((t) => `'${escapeSqlStringLiteral(t)}'`).join(",")}]`
);
}

const createdAtFilter = await this.#calculateCreatedAtFilter(url, params.createdAt);
Expand Down
24 changes: 24 additions & 0 deletions apps/webapp/test/realtimeClientEscapeSqlStringLiteral.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, it, expect } from "vitest";
import { escapeSqlStringLiteral } from "../app/services/realtimeClient.server";

describe("escapeSqlStringLiteral", () => {
it("leaves ordinary tag values unchanged", () => {
expect(escapeSqlStringLiteral("important")).toBe("important");
expect(escapeSqlStringLiteral("user_42")).toBe("user_42");
expect(escapeSqlStringLiteral("")).toBe("");
});

it("doubles a single quote", () => {
expect(escapeSqlStringLiteral("O'Brien")).toBe("O''Brien");
});

it("neutralizes the tags injection payload from #3739", () => {
const literal = `'${escapeSqlStringLiteral("test' OR '1'='1")}'`;
expect(literal).toBe("'test'' OR ''1''=''1'");
expect(literal.replace(/''/g, "")).toBe("'test OR 1=1'");
});

it("escapes every quote, not just the first", () => {
expect(escapeSqlStringLiteral("a'b'c'")).toBe("a''b''c''");
});
});